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