问题描述
在我的Rails应用程序4我有这两种模式:
类发票<的ActiveRecord :: Base的
#属性:日期,金额,open_amount等。
has_and_belongs_to_many:金
结束
类付款<的ActiveRecord :: Base的
#属性:日期,金额等。
has_and_belongs_to_many:发票
after_save的:update_invoices
...
私人
高清update_invoices
invoices.each做到|发票|
new_open_amount = invoice.open_amount - 量
invoice.update_column(:open_amount,new_open_amount)
结束
结束
结束
现在,创建一个付款单发票的作品,并更新发票的 open_amount
预期。
但是,如果一次性支付被用于更新的两个(或以上)发票?
支付金额
应分布在所有相关的发票,从具有最低 ID发票
和与具有最高 ID发票结束
。
例如,如果有三个发票的金额
100
每一个,并支付与创建的金额
250
,则发票的 open_amount
取值应变成这样的:
- 发票1:0
- 发票2:0
- 发票3:50
如何才能实现这一目标?我试图用一个循环,但未能由于我缺乏红宝石技能。
感谢您的帮助。
高清update_invoices
剩余=量
invoices.sort_by {| I | i.id}。每做|发票|
TMP = invoice.open_amount
接下来,除非剩余> 0#当钱没回报
new_open_amount = 0
如果剩余< invoice.open_amount
new_open_amount = invoice.open_amount - 剩余
结束
剩余=剩余 - TMP
invoice.update_column(:open_amount,new_open_amount)
结束
结束
In my Rails 4 application I have these two models:
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
Right now, creating a payment for a single invoice works and updates the invoice's open_amount
as expected.
But what if one payment is used to update two (or more) invoices?
The payment amount
should be distributed over all associated invoices, starting with the invoice that has the lowest id
and ending with the invoice that has the highest id
.
For example, if there are three invoices with an amount
of 100
each, and a payment is created with an amount
of 250
, then the invoice's open_amount
s should turn out like this:
- Invoice 1: 0
- Invoice 2: 0
- Invoice 3: 50
How can this be achieved? I tried using a loop but failed due to my lack of Ruby skills.
Thanks for any help.
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
这篇关于如何创造的Rails付款时更新相关联的发票?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!