Rails:Master中基于Detail的计算列

时间:2013-11-20 12:00:21

标签: ruby-on-rails

我有一些Master-Detail形式的表格。

create_table "invoice" do |t|
  t.integer  "serial_no"
  t.decimal  "amount"
end

create_table "line" do |t|
  t.integer  "item_id"
  t.decimal  "amount"
end

create_table "discount" do |t|
  t.integer  "discount_type_id"
  t.decimal  "amount"
end

具有从发票到行和折扣的has_many关系。

has_many :lines, inverse_of: :invoice, dependent: :destroy
has_many :discounts, inverse_of: :invoice, dependent: :destroy

UPDATE :也许我应该补充一点,我通过嵌套属性提取整个信息

accepts_nested_attributes_for :lines, allow_destroy: true
accepts_nested_attributes_for :discounts, allow_destroy: true

所有表都有一个金额列,我想在保存时汇总Invoice中的金额列。

def calculate_invoice_amount
  self.amount = line.sum(:amount) - discount.sum(:amount)
end

但这不起作用,因为行记录(可能)在发票记录后保存。

是否有标准方法使用详细信息表中的计算值更新主表?

PS:我期望的一个响应是总是可以从Line汇总金额,但是如果有频繁查询汇总信息,那么拥有更多的从属表会变得很麻烦

1 个答案:

答案 0 :(得分:0)

您可以使用before_save回调

class Line < ActiveRecord::Base
  before_save :update_invoice

  private
    def update_invoice
      self.invoice.calculate_invoice_amount if amount_changed?
    end
end

class Discount < ActiveRecord::Base
  before_save :update_invoice

  private
    def update_invoice
      self.invoice.calculate_invoice_amount if amount_changed?
    end
end