class AddPraisesCountToMemos < ActiveRecord::Migration[5.2] def change add_column :memos, :praises_count, :integer, :default => 0 memos = Memo.includes(:praise_treads).all memos.find_each do |m| puts("####{m.id}") praises_count = m.praise_treads.select{|pt| pt.praise_or_tread == 1}.count m.update_column(:praises_count, praises_count) end end end