class SyncIvalidUsers < ActiveRecord::Migration[5.2] def change users = User.where.not(id: 2).find_by_sql("select count(*) as user_count, login from users group by login having user_count>1") users.each do |user| valid_users = User.where(login: user.login) valid_users.each do |valid_user| unless valid_user.lastname.present? valid_user.delete end end end mail_users = User.where.not(id: 2).find_by_sql("select count(*) as user_count, mail from users where mail is not null group by mail having user_count>1") mail_users.each do |mail_user| valid_mail_users = User.where(mail: mail_user.mail) valid_mail_users.each do |valid_mail_user| unless valid_mail_user.lastname.present? valid_mail_user.delete end end end phone_users = User.where.not(id: 2).find_by_sql("select count(*) as user_count, phone from users where phone is not null group by phone having user_count>1") phone_users.each do |phone_user| valid_phone_users = User.where(phone: phone_user.phone) valid_phone_users.each do |valid_phone_user| unless valid_phone_user.lastname.present? valid_phone_user.delete end end end end end