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

    add_index :salesman_channels, [:salesman_id, :school_id], unique: true
  end
end
