Update the Post counter caches when adding the counter cache column

This commit is contained in:
Raphael Sofaer 2011-07-05 08:47:40 -07:00
parent ecd79766ce
commit 130914267b

View file

@ -1,6 +1,11 @@
class CounterCacheOnPostLikes < ActiveRecord::Migration class CounterCacheOnPostLikes < ActiveRecord::Migration
class Post < ActiveRecord::Base; end
def self.up def self.up
add_column :posts, :likes_count, :integer, :default => 0 add_column :posts, :likes_count, :integer, :default => 0
execute <<SQL if Post.count > 0
UPDATE posts
SET posts.likes_count = (SELECT COUNT(*) FROM likes WHERE likes.post_id = posts.id)
SQL
end end
def self.down def self.down