Rails ActiveRecord更新头记录

时间:2014-01-12 16:14:28

标签: ruby-on-rails rails-activerecord

我有一个资源发票和一个资源 invoiceline

当我创建,更新或删除发票时,父母的总和列,发票应该更新。

如何在铁轨中实现这一目标?

2 个答案:

答案 0 :(得分:1)

您可以将counter_cache选项传递给belongs_to关联。对于您的模型,您可以按如下方式定义belongs_to关联:

class InvoiceLine < ActiveRecord::Base
  belongs_to :invoice, dependent: :destroy, counter_cache: :sum_column
end

请注意,您的sum_column表格中应该包含列名invoices(例如上面的示例)。

答案 1 :(得分:1)

你可以用回调来做到这一点,比如

class InvoiceLine < ActiveRecord::Base
  after_destroy :calculate_invoice_sum
  after_save :calculate_invoice_sum

  belongs_to :invoice

  def calculate_invoice_sum
    if invoice
      invoice.calculate_invoice_sum
    end
  end
end

class Invoice < ActiveRecord::Base
  has_many :invoice_lines

  def calculate_invoice_sum
    # assuming InvoiceLine has an amount attribute
    total = invoice_lines.sum(&:amount)
    update_attribute(:sum, total)
  end
end

你可能想要before_回调而不是after,但我认为在这种情况下更有意义

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

http://api.rubyonrails.org/classes/Enumerable.html#method-i-sum