Skip to content

Instantly share code, notes, and snippets.

@nplusp
Created February 18, 2016 09:27
Show Gist options
  • Save nplusp/264d732e840ad13a490b to your computer and use it in GitHub Desktop.
Save nplusp/264d732e840ad13a490b to your computer and use it in GitHub Desktop.
Counter cache migration hack
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