class MigrateCourseShixunHomeworkPosition < ActiveRecord::Migration[5.2] def change Course.find_each do |course| puts course.id course.practice_homeworks.order("IF(ISNULL(homework_commons.publish_time),0,1), homework_commons.publish_time DESC, homework_commons.created_at DESC").reverse.each_with_index do |homework, index| homework.update_columns(position: index + 1) end end end end