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