可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.