diaspora/db/migrate/20110911213207_counter_cache_on_post_comments.rb.rb
2011-09-11 15:02:24 -07:00

14 lines
409 B
Ruby

class CounterCacheOnPostComments < ActiveRecord::Migration
class Post < ActiveRecord::Base; end
def self.up
add_column :posts, :comments_count, :integer, :default => 0
execute <<SQL if Post.count > 0
UPDATE posts
SET posts.comments_count = (SELECT COUNT(*) FROM comments WHERE comments.post_id = posts.id)
SQL
end
def self.down
remove_column :posts, :comments_count
end
end