What's the best way - or, indeed, any way - to calculate a running total in Rails?
I have a model, Sale. It has a quantity column and a sales_value column. I need to populate a third column, total_quantity, with the sum of the quantity values of the previous records, when the table is sorted by isbn_id, then channel_id, then invoice_date. This sets all sorts of sensible database management alarm bells ringing, so I'm wondering if it's even possible.
The reason for needing this cumulative sum is to apply a percentage to the sales where the cumulative quantity is within a particular range. I can't use an average sales value across all records, because the margin on sales can vary dramatically over time - so I'd apply an average to a bunch of sales which might over or under pay the royalty payee.
So. Should I do a before_save callback on the Sale model, and update_attribute, somehow? Is there a method to return the value of the previous record when the table is sorted in a particular way? Or should I dump all Sale records into an array and maybe use inject to accumulate the running total?
Any ideas most welcome, thanks in advance.
Update: subsequent question asked here.
Do not use inject (srsly). The best way to do this is to use the SQL group commands and/or the Calculations methods in activerecord (like sum)
http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html