Counter Cache Column


/ Published in: Rails
Save to your folder(s)

A great way to improve the performance of your web app, by using a column in the projects table which stores the number of task associated with it, seen in railscast #23


Copy this code and paste it in your HTML
  1. class AddTaskCount < ActiveRecord::Migration
  2. def seld.up
  3. add_column :projects, :tasks_count, :integer, :default => 0
  4. Project.reset_column_information
  5. Project.find(:all).each do |p|
  6. p.update_attribute :tasks_count, p.tasks.length
  7. end
  8. end
  9.  
  10. def self.down
  11. remove_column :projects, :tasks_count
  12. end
  13. end
  14.  
  15. --
  16.  
  17. class Task < ActiveRecord::Base
  18. belongs_to :project, :counter_cache => true
  19. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.