我是新來的rails,並且正在開發我的第一個rails項目之一,它是發票窗體中嵌套行項目的發票應用程序。我想在保存發票之前計算總髮票。如果只是在保存過程中添加了項目,我可以很好地保存它,但如果其中一個嵌套行項目被標記爲刪除,則不會正確計算總計。我將不得不返回並再次保存以獲得正確的總計費用。Rails嵌套窗體,在嵌套項目中計算值
class Invoice < ActiveRecord::Base
attr_accessible :job_name, :items_attributes, :tax1, :tax2, :subtotal
before_save :calculate_totals
has_many :items, :dependent => :destroy
accepts_nested_attributes_for :items, allow_destroy: true
private
def calculate_totals
self.subtotal = 0
self.items.each do |i|
self.subtotal = self.subtotal + (i.quantity * i.cost_per)
end
end
end
我注意到這是如何不同於PARAMS但問題條目記錄與請求PARAMATERS上市:_destroy =真
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"+OqRa7vRa1CKPMCdBrjhvU6jzMH1zQ=",
"invoice"=>{"client_id"=>"1",
"job_name"=>"dsdsadsad",
"items_attributes"=>{"0"=>{"name"=>"jhksadhshdkjhkjdh",
"quantity"=>"1",
"cost_per"=>"50.0",
"id"=>"21",
"_destroy"=>"false"},
"1"=>{"name"=>"delete this one",
"quantity"=>"1",
"cost_per"=>"10.0",
"id"=>"24",
"_destroy"=>"true"}}},
"commit"=>"Update Invoice",
"id"=>"8"}
感謝您幫助。
感謝您編寫此解決方案,它幫助我解決了我的問題 – widjajayd