#23 Counter Cache Column

#migrations/006_add_tasks_count.rb
def self.up
  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
end

def self.down
  remove_column :projects, :tasks_count
end

#models/task.rb
belongs_to :project, :counter_cache => true

#projects/index.rhtml
<%= pluralize project.tasks.size, 'task' %>

你可能感兴趣的:(Ruby,Rails)