Created
February 18, 2016 09:27
-
-
Save nplusp/264d732e840ad13a490b to your computer and use it in GitHub Desktop.
Counter cache migration hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AddCommentsCountToPosts < ActiveRecord::Migration | |
def change | |
change_table :posts do |t| | |
t.integer :comments_count, default: 0 | |
end | |
reversible do |dir| | |
dir.up { data } | |
end | |
end | |
def data | |
execute <<-SQL.squish | |
UPDATE posts | |
SET comments_count = (SELECT count(1) | |
FROM comments | |
WHERE comments.post_id = posts.id) | |
SQL | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment