For a rails 3 class like
class Item < ActiveRecord::Base
has_many :production_runs
has_many :deliveries
end
where both production runs and deliveries have the attribute "quantity" for the number of items in that particular production or delivery.
I would like to query items and (perhaps using a scope?) add the Sum() of the quantities from both tables to the result. Something like:
select items.*, (select SUM(product开发者_开发知识库ion_runs.quantity) as runs from production_runs where production_runs.item_id = 42), (select SUM(deliveries.quantity) as dels from deliveries where deliveries.item_id = 42) from items where items.id = 42;
Which gives the correct result for a single item, but I'd like to somehow roll those sums into a more general query.
I have tried a variety of adding scopes to both Item and the ProductionRun and Delivery classes with no luck. It would be nice to use a scope as I could chain it with other conditions as needed, but really i'd be happy with any general solution that was more optimal than just finding sets of items and then iterating.
Anyone know the best way to do this?
Thanks
scope :sum_column_name, lambda{
sum("column name")}
should work
精彩评论