Jenny Blunt
Jenny Blunt

Reputation: 1596

Column Calculations Rails 3

my app has invoices and invoice_items. Each invoice has many invoice_items.

In my invoice_items model, I have a calculation to work out the total:

def total
   @total ||= quantity.to_d * price
end

That works fine. What I'm trying to do is calculate the sum of the totals and I'm stuck.

In the console, I've tried this:

invoice = Invoice.first
invoice.invoice_items.sum(:total)

But I get an error saying :total doesn't exist. Which I guess it doesn't.

My question is how I can go about doing this calculation?

-- UPDATE --

I've tried the following as per @paukul's answer:

invoice.invoice_items.sum(&:total)

This gives the error:

ArgumentError: wrong number of arguments (1 for 2)

Thanks

Upvotes: 0

Views: 662

Answers (1)

Pascal
Pascal

Reputation: 6030

you are calling .sum on the whole invoice_items array (which obviously doesn't know the .total method) and not each individual invoice item. To make it work you want to use the block version of sum which yields every single item in the array to the block and sums up their results.

with the symbol to proc syntactic sugar, you are almost there. Try invoice.invoice_items.all.sum(&:total) which is equivalent to invoice.invoice_items.inject(0) { |sum, item| sum + item.total }

see the RDoc for Enumerable#sum

Upvotes: 3

Related Questions