【问题标题】:Rails Getting a running balance with ordered list - summation virtual attributeRails 通过有序列表获得运行平衡 - 求和虚拟属性
【发布时间】: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


    【解决方案1】:

    问题是您使用日期作为条件,这对同一天的记录没有区别。为了解决这个问题,使用 ID 来区分记录。

    def balance_to_item(date, id)
     ...
      rent_logs.where(["dated < ? or (dated = ? and ID <= ?)", date, date, id]).sum(:credit) - 
      rent_logs.where(["dated < ? or (dated = ? and ID <= ?)", date, date, id]).sum(:debit)
    end
    

    您需要指定交易项目来计算余额。

    【讨论】:

    • 如果 id 不是订购的一部分,这会起作用吗?例如,id 5 可能紧跟在 id 6 之后,而不是自然计数 4,5,6 它可能看起来像 20,6,5,7,8。但我使用 :credit 进行排序,所以可能会这样做......
    • 如果 id 不是订单的一部分,那么它会导致余额订单有些混淆。如果您使用信用来订购,那么空值也会混淆,这就是为什么我建议您使用 ID 代替,即使在订购中也是如此。它只会在给定日期内更改订单,因此不会混淆。
    • 是的,一旦我将关联的顺序简化为 [:dated,:id],这将非常有效,并且比我正在设计的任何其他实现都更简单、更清晰。谢谢马兹!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多