0

我想在客户付款后跟踪发票余额,我该如何实现?

我有嵌套资源

resources :invoices do
  resources :payments
end

发票模型如下:

class Invoice < ActiveRecord::Base

 belongs_to :customer, :inverse_of => :invoices
 attr_accessible :due_date, :invoice_date, :reading_ids, :customer_id, :customer, :status, :amount,     :balance

 has_many :invoice_items, :dependent => :destroy
 has_many :payments, :dependent => :destroy
end

支付模式如下:

class Payment < ActiveRecord::Base
  attr_accessible :amount, :method, :payment_date, :reference_no, :invoice_id
  belongs_to :invoice
end

每当客户付款时,我想从余额中减去付款并为该发票存储新余额。这将成为发票的新余额。

我怎样才能做到这一点?

4

1 回答 1

2

实现您想要的一种方法是使用ActiveRecord::Callbacks

class Payment < ActiveRecord::Base
  attr_accessible :amount, :method, :payment_date, :reference_no, :invoice_id
  belongs_to :invoice
  after_create :update_invoice_balance

  def update_invoice_balance
    current_balance = self.invoice.balance
    self.invoice.update_attributes(balance: current_balance - self.amount)
  end
end

您可以尝试的另一种方法是accepts_nested_attributes_for在您的Invoice模型中使用:

class Invoice < ActiveRecord::Base

  belongs_to :customer, :inverse_of => :invoices
  attr_accessible :payments_attributes, :due_date, :invoice_date, :reading_ids, :customer_id, :customer, :status, :amount, :balance

  has_many :invoice_items, :dependent => :destroy
  has_many :payments, :dependent => :destroy

  accepts_nested_attributes_for :payments
end

在这种情况下,您将从invoces#edit页面创建付款,并且可以这样构建表单:您将拥有“立即付款”按钮,该按钮将注入payments/_new_forminvoices/_edit_form然后任何时候用户将值输入到amount字段中payments/_new_form,您将更新余额字段invoices/_edit_form的值与使用 JavaScript的amount字段的值。payments/_new_form提交invoices/_edit_form将保存这两个对象。如果您采用这种方法,请查看nested_form gem,它会使事情变得更容易。但是,我仍然推荐回调方法,因为它保证每次都更新发票余额(即使您从控制台而不是 UI 进行更新)。

于 2013-05-03T12:51:31.630 回答