How would I save multiple records at once in Rails?

匿名 (未验证) 提交于 2019-12-03 02:18:01

问题:

How would I save this array in one call with Rails?

tax_rates = [{   :income_from => 0   :income_to  => 18200   :start => "01-07-2013"   :finish => "30-06-2014"   :rate => nil   :premium => nil   },{   :income_from => 18201   :income_to  => 37000   :start => "01-07-2013"   :finish => "30-06-2014"   :rate => 0.19   :premium => nil   },{     :income_from => 18201     :income_to  => 37000     :start => "01-07-2013"     :finish => "30-06-2014"     :rate => 0.19     :premium => nil     }] 

Can I just call Rails.create(tax_rates)?

Also, is there a way to remove duplicate symbols so they look neater?

回答1:

tax_rates.map {|tax_rate| TaxRate.new(tax_rate).save }  

This way you'll retrieve an array with true and false to know which did succeed and which didn't.



回答2:

Your example is almost correct.

Use ActiveRecord::Persistence#create, which can accept an array of hashes as a parameter.

tax_rates = [   {     income_from: 0,     income_to: 18200,     start: "01-07-2013",     finish: "30-06-2014",     rate: nil,     premium: nil,   },   {     income_from: 18201,     income_to: 37000,     start: "01-07-2013",     finish: "30-06-2014",     rate: 0.19,     premium: nil,   },   # ... ]  TaxRate.create(tax_rates)  # Or `create!` to raise if validations fail 


回答3:

If you want all of them to be saved .or, non of them to be saved even if one fails, you can use 'ActiveRecord::Base.transaction'

e.g.

ActiveRecord::Base.transaction do      tax_rate.each do |tax_rt|          TaxRate.new(tax_rt).save       end  end 


回答4:

I am not sure about rails < 4.2 but I have tried it in rails 4.2 you can simply do this

TaxRate.create(tax_rt) 


回答5:

Here is an example like yours:

a = []  a << B.new(:name => "c") a << B.new(:name => "s") a << B.new(:name => "e") a << B.new(:name => "t") 

The array is saved all at once with:

a.each(&:save) 

This will call B#save on each item in the array.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!