Calculations & joins

I want to have a sum of an order by doing something like:

select sum(items.price) from order, items where order.item_id =
items.id

Since Order and Item class are related (using “belongs_to”), I thought
I could use:

Order.sum(‘items.price’)

But that doesn’t work as expected… I have to use:

Order.sum(‘items.price’, :joins => ‘left outer join items on
items.id=item_id’)

Isn’t ActiveRecord::Calculations supposed to know that I’m asking for
a join? Why am I supposed to write it?

Isn’t ActiveRecord::Calculations supposed to know that I’m asking for
a join? Why am I supposed to write it?
sum() wont automatically make the joins for you - it only pulls that
data when it’s needed.

If you want a sum of all item prices, you do:
Item.sum(‘price’)

If you want a sum of the prices of items within a specific order, you
do:
order = Order.find(1234)
order.items.sum(‘price’)

You should also be able to do:
Order.sum(‘items.price’, :include => ‘items’)

Hope that helps,

Steve

You should also be able to do:
Order.sum(‘items.price’, :include => ‘items’)

That’s the stuff! Great! Thank you!
But “include” it’s not described in the docs for “calculate”, only for
“count”! I think it should be added to the docs…

http://api.rubyonrails.org/classes/ActiveRecord/Calculations/
ClassMethods.html#M000953