I have the object Tool
with a price
and a ToolsOrder
for every sale with a quantity
. I need to show total of the sales
Tool has many: tools_orders ToolsOrders belongs_to: tool
I think in something like this or similar? I can’t make it work
ToolsOrder.sum("quantity * Tool.price")
How can I calculate the total sum?
Advertisement
Answer
Sometimes it’s useful to read error messages that the code gives you. Assuming the error you got was: missing FROM-clause entry for table "tool"
. This is saying that you’re querying for price
from table tool
, but there is no such table in the current query.
You’re missing a join.
ToolsOrder.joins(:tool).sum("quantity * tools.price")
It can be made safer using Arel though if you’d like.
ToolsOrder.joins(:tool).sum(ToolsOrder.arel_table[:quantity] * Tool.arel_table[:price])
Now there’s not pure sql, that is easy to make typos in (Tool vs tools) and is open to sql injections.