简体   繁体   中英

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

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. Is there a way to create multiple model instances at once?

I want to write like 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM