#23 Counter Cache Column

If you need to display the record count for a has_many association, you can improve performance by caching that number in a 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' %>

你可能感兴趣的:(cache,UP,performance)