我是 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
我注意到这与参数有何不同,但问题项记录在请求的参数中列出,并带有 :_destroy = true
{"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"}
感谢您的帮助。
最佳答案
我找到了一个似乎有效的解决方案:
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|
unless i.marked_for_destruction?
self.subtotal += (i.quantity * i.cost_per)
end
end
end
关键是marked_for_destruction这个方法?在本例中,我正在检查未标记为销毁的项目。以下是 Rails api 的链接,对其进行了解释:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
谢谢 史蒂夫
关于ruby-on-rails - Rails 嵌套形式,从嵌套项目计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390512/