如何在Rails中一次创建多个模型实例

时间:2016-08-04 21:15:57

标签: ruby-on-rails

我有这样的方法:

codes.each do |code|
  company = Company.find_or_create_by(code: code)
  company.foo = some_value
  company.bar = some_value2
  company.save
end

为了加快速度,我想用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

但每次执行SQL命令时find_or_create_by都会运行。 有没有办法一次创建多个模型实例?

我想写成Company.create_all_if_not_exist(code: codes)

1 个答案:

答案 0 :(得分:0)

我看到了更好的方法:

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