Rails:基于细节的Master中的计算列



我有一些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

所有表都有一个金额列,我想在保存时聚合发票中的金额列。

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

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

是否有一种标准的方法来用明细表中的计算值更新主表?

PS:我希望得到的回应之一是,总是可以从Line汇总金额,但由于有更多的依赖表,如果频繁查询聚合信息

,这将变得很麻烦

您可以使用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

最新更新