class AddPositionForInforms < ActiveRecord::Migration[5.2] def change add_column :informs, :position, :integer, :default => 1 course_ids = Inform.where(container_type: 'Course').pluck(:container_id).uniq courses = Course.where(id: course_ids) courses.find_each do |course| next if course.informs.count == 1 informs = course.informs.order("created_at asc") informs.each_with_index do |inform, index| inform.update_attribute(:position, index+1) end end end end