Pas*_*per 18 ruby ruby-on-rails
如何使用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
}]
Run Code Online (Sandbox Code Playgroud)
我可以打电话Rails.create(tax_rates)
吗?
还有,有没有办法删除重复的符号,使它们看起来更整洁?
Den*_*nis 26
你的例子几乎是正确的.
使用ActiveRecord::Persistence#create
,可以接受哈希数组作为参数.
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
Run Code Online (Sandbox Code Playgroud)
apn*_*ing 14
tax_rates.map {|tax_rate| TaxRate.new(tax_rate).save }
Run Code Online (Sandbox Code Playgroud)
这样你就可以检索一个数组,true
并false
知道哪个成功了,哪个没有成功.
如果你想要保存所有这些,或者即使一个失败也不保存它们,你可以使用'ActiveRecord :: Base.transaction'
例如
ActiveRecord::Base.transaction do
tax_rate.each do |tax_rt|
TaxRate.new(tax_rt).save
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20077 次 |
最近记录: |