0

我試圖在有序列表上獲取每筆交易的當前餘額,一個簡單的求和(信用額度記錄 - 借記記錄)。Rails使用有序列表獲取運行餘額 - 求和虛擬屬性

挑戰在於交易通常是亂序輸入的,交易日誌按照「日期」字段(顯示應該輸入的日期)和「信用」先排序(以便顯示付款在同一天的賬單之前)。

協會進行排序:

has_many :rent_logs, :order => [:dated, "credit desc"] 

相關數據在simular以下

[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 

問題是我不希望它通過感興趣的日期得到所有事先的差異。我希望它通過*當前記錄獲得所有先前的差異。

有沒有其他明顯的屬性來做我可以想到的條件或過濾器。我能想到的最好的解決方案是一個醜陋的,可能應該讓我解僱......:

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

感謝 菲爾

回答

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 

您需要指定交易項目以計算最多的餘額。

+0

如果ID不是訂購的一部分,這項工作是否會起作用?例如,id 5可能在id 6之後出現,而不是自然計數4,5,6,它可能看起來像20,** 6 **,5,7,8。但我使用:信用排序,所以這可能會做到這一點... – nevieandphil 2013-03-05 11:37:16

+0

如果id不是訂購的一部分,那麼它會導致平衡訂單有些混合。如果您使用信用卡進行訂購,那麼空值也會混淆東西,這就是爲什麼我建議您改用ID,即使在訂購時。它只會改變某一天內的訂單,所以不會混淆。 – Matzi 2013-03-05 12:04:24

+0

是的,一旦我簡化了[:dated,:id]這個關聯的順序,這個工作就非常好,並且比我正在合作的其他任何實現都更簡單和更簡潔。謝謝Matzi! – nevieandphil 2013-03-05 12:59:48