Files
growstuff/db/migrate/20191226025225_post_comment_counter_cache.rb
Daniel O'Connor f381ba29cc Merge pull request #4534 from Growstuff/Layout/HeredocIndentation
Rubocop: Layout/HeredocIndentation
2026-04-23 22:07:41 +09:30

24 lines
495 B
Ruby

# frozen_string_literal: true
class PostCommentCounterCache < ActiveRecord::Migration[5.2]
def change
change_table :posts do |t|
t.integer :comments_count, default: 0
end
reversible do |dir|
dir.up { set_counter_value }
end
end
def set_counter_value
execute <<~SQL.squish
UPDATE posts
SET comments_count = (
SELECT count(1)
FROM comments
WHERE comments.post_id = posts.id
)
SQL
end
end