class AddIsInvalidToStudentWorksScores < ActiveRecord::Migration[5.2]
  def change
    # add_column :student_works_scores, :is_invalid, :boolean, default: false

    StudentWorksScore.where("score is not null").order("id desc").find_each do |score|
      unless score.is_invalid
        if score.student_work.present?
          puts score.id
          work = score.student_work

          # 如果分数是调整分 则之前的所有分都无效
          if score.is_ultimate
            work.student_works_scores.where("score is not null and id < #{score.id}").update_all(is_invalid: 1)

            # 如果是同一个用户角色的重复评分，则之前的评分都无效
          elsif work.student_works_scores.where("user_id = #{score.user_id} and reviewer_role = #{score.reviewer_role}
                                                  and score is not null and id < #{score.id}").count > 0
            work.student_works_scores.where("user_id = #{score.user_id} and reviewer_role = #{score.reviewer_role}
                                             and score is not null and id < #{score.id}").update_all(is_invalid: 1)
          end
        end
      end
    end
  end
end
