I am new to Ruby / Rails, so this is possible (hopefully) a simple question that I just don't know the answer to.
I am implementing an accounting / billing system in Rails, and I am trying to track the current balance status after each transaction in order to display it in a view, as shown below:
Date Description Charges ($) Credits ($) Balance ($)
Mar 2 Activity C $ 4.00 - $ 7.50
Feb 25 Payment for Jan $ 8.00 - $ 3.50
Feb 23 Activity B $ 1.50 - $ 11.50
Feb 20 Activity A $ 2.00 - $ 10.00
Each transaction (also known as a position) is stored in the database with all the values above (Date, Description, Amount), except for the Balance. I can’t keep the balance for each transaction in the database, because it can change if something happens to an earlier transaction (for example, a payment that was published later was not executed later). Therefore, I need to calculate it "on the fly" for each position, and the value for the Balance for the position depends on the value for the position in front of it ("Balance = balance of the pre-position" + "Amount" for this position, i.e.)
So here is my question. My current (inept) way to do this is that in my LineItem model, I have a balance method that looks like this:
def balance
prev_balance = 0
last_line_item = Billing::LineItem.get_last_line_item_for_a_ledger(self.issue_date,self.ledger_item_id)
if last_line_item
prev_balance = last_line_item.balance
.. some other stuff...
end
prev_balance + (-1*net_amount)
end
, , . ?