I have this code that works with shipment has one invoice, but now I had to change it to shipment has many invoices. How can I modify the following code to reflect the new association?
@totals = {
:overall => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_total },
:paid => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_amount_paid },
:balance => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_open_balance }
}
I would do something like this:
Note: Enumerable#reduce, along with many other methods in
Enumerable, has the ability to work with a block or a symbol that names a method or operator. This allows you to replace[1,2,3,4,5].reduce{ |sum, x| sum + x }with[1,2,3,4,5].reduce(:+)Also, if no argument is given, the first value in the collection is assumed to be the initial value of the memo.
As tokland points out, you will want to pass in the initial value of the memo as 0, in case the array is empty. This prevents you from getting a
@totals[:balance] == nil.