class AddIndexToUserIdAndShixunIdForShixuns < ActiveRecord::Migration[5.2]
  def change
    shixun_members = ShixunMember.select("count(*) cnt, shixun_members.*").group(:user_id, :shixun_id).having("cnt > 1")
    puts "shixun_members: #{shixun_members.map{|sm| sm.id}}"
    shixun_members.each do |sm|
      s = ShixunMember.where.not(id: sm.id).where(user_id: sm.user_id, shixun_id: sm.shixun_id)
      puts "s: #{s.map{|sm| sm.id}}"
      s.delete_all
    end

    add_index :shixun_members, [:user_id, :shixun_id], unique: true

  end
end
