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