Nick
Nick

Reputation: 859

How do I perform multiplication within a group in Rails controller?

I have an Orders model which contains a beverage ID and both quantity and unit price, which are multiplied together to give a total order value.

In another part of my app, I need to group orders by the beverage ID and then sum all of the order values to give the total stock value on hand.

When I need to calculate the total quantity on hand, I do it like this in the controller:

@delivery_total = Order.group(:beverage_id).sum(:quantity, :conditions => {:orderable_type => 'Delivery'})

(I filter by orderable_type as there are also returns)

So I thought, when I need to calculate the total order value, it would be the following:

@delivery_value = Order.group(:beverage_id).sum((:quantity * :price), :conditions => {:orderable_type => 'Delivery'})

But that doesn't work, giving the error

undefined method `*' for :quantity:Symbol

I'm afraid I'm still learning here... Can anyone advise the right way to do this?

Upvotes: 1

Views: 752

Answers (1)

Jun Zhou
Jun Zhou

Reputation: 3080

The first parameter of sum should be a String, like this:

@delivery_total = Order.group(:beverage_id).sum("quantity * price", :conditions => {:orderable_type => 'Delivery'})

Upvotes: 1

Related Questions