Skip to content

Instantly share code, notes, and snippets.

@andreaseriksson
Created May 27, 2013 09:04
Show Gist options
  • Save andreaseriksson/5655982 to your computer and use it in GitHub Desktop.
Save andreaseriksson/5655982 to your computer and use it in GitHub Desktop.
RAILS Counter Cache
#Migration
add_column :projects, :tasks_count, :integer, :default => 0
Project.reset_column_information
Project.find(:all).each do |p|
Project.update_counters p.id, :tasks_count => p.tasks.length
end
#Model
belongs_to :project, :counter_cache => true
#View
pluralize project.tasks.size, 'task'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment