Damian Janowski
2008-May-20 20:49 UTC
New add_counter_cache_column to ActiveRecord migrations
Hi everyone, I submitted a patch that creates a new add_counter_cache_column method available to migrations. Apart from creating the <association>_count column for you (with default 0), this will update the counter with the current value for each row. So: def self.up add_counter_cache_column :posts, :comments end Will generate the comments_count column on posts, plus give it initial values, just like doing: Post.reset_column_information Post.find(:all).each do |post| Post.update_counters post.id, :comments_count => post.comments.count end I found adding these columns is a very common practice when tuning for performance as development evolves. Updating the counters with their initial value seems like a must to prevent data corruption (imagine your tests breaking after creating the magic column -- everyone calling #size on the association suddenly gets 0). Small doc update and tests: http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/228-add-add_counter_cache_column-to-activerecord-migrations Cheers Damian --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group. To post to this group, send email to rubyonrails-core@googlegroups.com To unsubscribe from this group, send email to rubyonrails-core-unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en -~----------~----~----~----~------~----~------~--~---