class AddRootIdToMemos < ActiveRecord::Migration def change add_column :memos, :root_id, :integer add_index :memos, :root_id def get_base_parent comment comm = comment while comm.parent comm = comm.parent end comm end count = Memo.all.count / 30 + 2 transaction do for i in 1 ... count do i Memo.page(i).per(30).each do |memo| unless memo.parent.nil? parent = get_base_parent memo memo.update_column('root_id', parent.id) end end end end end end