开发者

Multiple SUM statements or subqueries in Rails 3, possibly using scope. Anyone?

开发者 https://www.devze.com 2023-02-05 00:03 出处:网络
For a rails 3 class like class Item < ActiveRecord::Base has_many :production_runs has_many :deliveries

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

0

精彩评论

暂无评论...
验证码 换一张
取 消