如何在Rails中创建付款时更新关联的发票?

时间:2015-02-01 19:22:19

标签: ruby-on-rails ruby activerecord

在我的Rails 4应用程序中,我有这两个模型:

class Invoice < ActiveRecord::Base

  # Attributes: date, amount, open_amount, etc.

  has_and_belongs_to_many :payments

end

class Payment < ActiveRecord::Base

  # Attributes: date, amount, etc.

  has_and_belongs_to_many :invoices

  after_save :update_invoices

  ...

  private

  def update_invoices
    invoices.each do |invoice|
      new_open_amount = invoice.open_amount - amount
      invoice.update_column(:open_amount, new_open_amount)
    end
  end

end

现在,为单个发票创建付款可以按预期更新发票的open_amount

但如果使用一次付款来更新两个(或更多)发票呢?

付款amount应分配到所有相关发票上,从最低id的发票开始,到最高id的发票结束。

例如,如果有三张发票各自amount 100,而付款是使用amount 250创建的,那么发票的{{} 1}} s应该是这样的:

  • 发票1:0
  • 发票2:0
  • 发票3:50

如何实现这一目标?我尝试使用循环但由于缺乏Ruby技能而失败。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

  def update_invoices
    remaining = amount
    invoices.sort_by{|i| i.id }.each do |invoice|
      tmp = invoice.open_amount
      next unless remaining > 0  #when the money is gone return
      new_open_amount = 0
      if remaining < invoice.open_amount
        new_open_amount = invoice.open_amount - remaining
      end
      remaining = remaining - tmp
      invoice.update_column(:open_amount, new_open_amount)
    end
  end