class MigrateCourseTaskPosition < ActiveRecord::Migration[5.2]
  def change
    add_column :homework_commons, :position, :integer, :default => 0

    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
