[英]How to create multiple model instances at once in Rails
I have a method like this: 我有这样的方法:
codes.each do |code|
company = Company.find_or_create_by(code: code)
company.foo = some_value
company.bar = some_value2
company.save
end
And to make it faster I want to write it with update_all
为了使其更快,我想用update_all
编写它
codes.each do |code|
Company.find_or_create_by(code: code)
Company.where(code: code).update_all(foo: some_value, bar: some_value2)
end
But the find_or_create_by
run every time a SQL command. 但是find_or_create_by
每次都会执行SQL命令。 Is there a way to create multiple model instances at once? 有没有办法一次创建多个模型实例?
I want to write like Company.create_all_if_not_exist(code: codes)
. 我想写像Company.create_all_if_not_exist(code: codes)
。
I see a better way: 我看到一个更好的方法:
existing_companies = Company.where(code: codes)
existing_codes = existing_companies.pluck(:code) # +1 request
non_existing_codes = codes - existing_codes
attrs = {foo: some_value, bar: some_value2}
existing_companies.update_all(attrs) # +1 request
# + (codes - existing_codes) requests
non_existing_codes.each do |code|
Company.create({code: code}.merge(attrs))
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.