我有一个资源发票和一个资源 invoiceline 。
当我创建,更新或删除发票时,父母的总和列,发票应该更新。
如何在铁轨中实现这一目标?
答案 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