2013-09-29 55 views
11

我將如何使用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 
    }] 

可我只是叫Rails.create(tax_rates)

此外,有沒有辦法刪除重複的符號,使他們看起來整潔?

回答

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

這樣你會truefalse檢索數組知道這並獲得成功,哪些沒有。

+0

這是有益的,但如果我有索引,太像:{「0」 :{ :income_from => 0 .....},「1」:{:income_from => 18201 ...},「2」:{} ...} –

+0

我得到的解決方案只是使用'索引' - > |索引,tax_rate |。 –

1

這裏是像你這樣的一個例子:

a = [] 

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

的陣列與保存一次全部:

a.each(&:save) 

這將調用B#save在陣列中的每個項目。

4

如果你希望所有的人都得救。或者,他們不被保存,甚至如果失敗了,你可以使用的ActiveRecord :: Base.transaction'

例如

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

你舉的例子幾乎是正確的。

使用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 
+0

這不適合我。我可以保存散列,但驗證被「!」忽略或沒有。你是怎麼做到的? – theDrifter

2

我不知道軌< 4.2,但我已經嘗試過在導軌4.2,你可以簡單地做這

TaxRate.create(tax_rt) 
相關問題