class AddUniqIndexToEvaluationDistribution < ActiveRecord::Migration[5.2] def change sql = %Q(delete from student_works_evaluation_distributions where (user_id, student_work_id) in (select * from (select user_id, student_work_id from student_works_evaluation_distributions group by user_id, student_work_id having count(*) > 1) a) and id not in (select * from (select min(id) from student_works_evaluation_distributions group by user_id, student_work_id having count(*) > 1 order by id) b)) ActiveRecord::Base.connection.execute sql add_index :student_works_evaluation_distributions, [:student_work_id, :user_id], name: "index_on_student_work_id_and_user_id", unique: true remove_index :student_works_evaluation_distributions, :user_id end end