问题描述
如何使用 Rails 在一次调用中保存这个数组?
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
}]
我可以直接调用Rails.create(tax_rates)
吗?
另外,有没有办法去除重复的符号,让它们看起来更整洁?
Also, is there a way to remove duplicate symbols so they look neater?
推荐答案
一个不错的解决方案是使用 活动记录导入宝石.我现在推荐它内置的 Rails 批量 isert,因为它在违反约束的情况下的选项更加灵活.
A nice solution is to use the active record import gem. I recommend it over now builtin Rails bulk isert because its more flexible in the options in case of constraint violation.
TaxRate.import(
[:income_from, :income_to, :start, :finish, :rate, :premium],
tax_rates
)
它绝对比我的旧答案好,它会触发数组中每个条目的数据库提交:)
Its definitely better than my old answer which would trigger a db commit per entry in the array :)
旧答案:
tax_rates.map {|tax_rate| TaxRate.new(tax_rate).save }
通过这种方式,您将检索具有 true
和 false
的数组,以了解哪些成功了,哪些没有.
This way you'll retrieve an array with true
and false
to know which did succeed and which didn't.
这篇关于如何在 Rails 中一次保存多条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!