ruby-on-rails - Rails 嵌套形式,从嵌套项目计算值

标签 ruby-on-rails nested before-save

我是 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/

相关文章:

ruby-on-rails - 如何对对象数组进行排序?

ruby-on-rails - Rails 市场支付处理

mysql - Yii 在其他模型中调用 beforeSave() 来保存

ruby-on-rails - 使用多对多关系时如何插入行

java - 尝试创建使用两个用户输入值的嵌套 for 循环

ruby-on-rails-3 - Rails 3的嵌套脚手架生成器?

html - 嵌套的 Div\Grids 960 显示不正确

ruby-on-rails - 在相关模型中更改属性后运行 before_save

ruby-on-rails - rails 4 : how to use named scope with has_many associations