【发布时间】:2013-03-05 09:12:16
【问题描述】:
我正在尝试获取每笔交易的当前余额,即有序列表上的简单汇总(信用记录 - 借记记录)。
挑战在于,交易经常输入无序,交易日志按“日期”字段(显示应输入的日期)和“信用”排序(以便显示之前的付款)同一天的账单)。
关联排序:
has_many :rent_logs, :order => [:dated, "credit desc"]
数据与以下类似
[ID] Dated Label Credit Debit Balance [Needs excel summation look]
[20] 1/1/13 payment 600.0 -30 * [Should be: 600 ]
[1 ] 1/1/13 Rent Due 630.0 -30 [Ok here : -30 ]
[2 ] 2/1/13 Rent Due 630.0 -660 [Ok here : -660]
[28] 2/6/13 Late Fee 50.0 -710 [Ok here : -710]
[7 ] 3/1/13 payment 1200.0 -140* [Should be: 490 ]
[3 ] 3/1/13 Rent Due 630.0 -140 [Ok here : -140]
* Indicates massive fail on running balance
我是通过在租赁模型中运行以下方法得到的。
def balance_to_date(date)
...
rent_logs.where("dated <= ?", date).sum(:credit) - rent_logs.where("dated <= ?" ,date).sum(:debit)
#problem with above is that it calculates day by day, rather than record by record.
end
问题是我不希望它在感兴趣的日期之前获得所有先前的差异。我希望它通过 *current 记录获得所有先前的差异。
没有其他明显的属性可以做我能想到的条件或过滤器。我能想到的最好的解决方案是一个丑陋的解决方案,它可能会让我被解雇......:
def balance_to_transaction(id)
balance = rent_logs.where("dated <= ?", date-1.day).sum(:credit) - rent_logs.where("dated <= ?" ,date-1.day).sum(:debit)
rent_logs.where("dated = ?", date).each do |transaction|
balance += transaction.credit
balance -= transaction.debit
if (id == transaction.id)
break
end
end
balance
end
这不是正确的做法吗?
我正在使用 Rails 3.2.12、Ruby 1.9.3
谢谢 菲尔
【问题讨论】:
标签: sql ruby-on-rails ruby-on-rails-3 activerecord virtual-attribute