トランザクションごとの現在の残高を取得しようとしています。これは、順序付けられたリストの単純な合計(クレジットが記録されるまで-デビットが記録されるまで)です。
課題は、トランザクションが順不同で入力されることが多く、トランザクションログが「日付」フィールド(入力されるべき日付を示す)と最初に「クレジット」(請求前の支払いが表示されるように)で並べ替えられることです。同日)。
関連付けは並べ替えられます。
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
問題は、関心のある日付全体を通して、以前のすべての差を取得したくないということです。*現在のレコードを通じて、以前のすべての違いを取得したいと思います。
私が考えることができる条件やフィルターを実行するための他の明白なプロパティはありません。私が考えることができる最善の解決策は、おそらく私を解雇するはずの醜い解決策です...:
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、Ruby1.9.3を使用しています
ありがとうフィル