批量插入并忽略重复记录
Bulk insert with ignore duplicate records
我正在尝试根据条件进行批量插入,如果电子邮件存在,它应该忽略该记录。
目前我的方法有点长。首先,我正在过滤不在用户 table 中的电子邮件,然后我正在执行插入,这会触发多个插入查询。我检查了 rails 6 我们有 insert_all 和 upsert_all 但不确定我们如何使用这些方法实现相同的目的。
user_email = ["aniket@rpxcorp.com", "assasdas@gmail.com"]
##Only find those users which doesn't exists in users table
user_email = user_email - User.all.pluck(:email)
records = []
role = Role.find_by(name: "admin")
user_email.each do |record|
records.push({email: record, password: "12345678", password_confirmation: "12345678", role: role})
end
#it will run multiple insert commands which I want to avoid
u = User.create(records)
根据@tadman 对任何由 devise 支持的模型的评论,我们不能进行批量插入
我正在尝试根据条件进行批量插入,如果电子邮件存在,它应该忽略该记录。 目前我的方法有点长。首先,我正在过滤不在用户 table 中的电子邮件,然后我正在执行插入,这会触发多个插入查询。我检查了 rails 6 我们有 insert_all 和 upsert_all 但不确定我们如何使用这些方法实现相同的目的。
user_email = ["aniket@rpxcorp.com", "assasdas@gmail.com"]
##Only find those users which doesn't exists in users table
user_email = user_email - User.all.pluck(:email)
records = []
role = Role.find_by(name: "admin")
user_email.each do |record|
records.push({email: record, password: "12345678", password_confirmation: "12345678", role: role})
end
#it will run multiple insert commands which I want to avoid
u = User.create(records)
根据@tadman 对任何由 devise 支持的模型的评论,我们不能进行批量插入