2014-03-06 80 views
1

我有一個模型和has_many關聯。Rails - 保存之前迭代has_many關聯的嵌套屬性

說,

class Invoice < ActiveRecord::Base 
    has_many :lines, class_name: 'InvoiceLine', inverse_of: :invoice, dependent: :destroy 
    accepts_nested_attributes_for :lines, reject_if: :invalid_line, allow_destroy: true 
end 

是否有可能對我來說,通過迭代線之前,(尤其是在更新)保存,無論是在InvoicesController或發票模型?

當我在更新期間對現有記錄進行迭代時,我得到的是舊行,而不是視圖中的更新行。

目前我在控制器中執行以下操作。我對此並不滿意。

total = params["invoice"]["lines_attributes"]. 
      map{|k,v| [v["amount"], v["_destroy"]]}. 
      select{|x| x[1] == "false"}. 
      map{|x| x[0].to_f}. 
      inject {|total, amount| total + amount} 
+0

這是可能的,但我需要看到controlle r提出具體建議 –

+0

我已經更新了這個問題,以及我目前正在做的事情。 –

回答

0

可以使用assign_attributesmarked_for_destruction?爲:

@ invoice.assign_attributes(PARAMS [:發票])
總= @ invoice.lines.select(&:marked_for_destruction)地圖。 (&:量)的.sum
@ invoice.save #save所有的數據庫