开发者

Finding the total stock amount of a product across all stores

I have a Shop model and a 开发者_Go百科Product model. I also have a StockItem model which joins the two - StockItem has shop_id, product_id and quantity attributes.

I need to find the total quantity of each product in stock across all the shops and the way I'm doing this at the moment feels a bit clunky:

quantity = 0
Product.first.stock_items.collect { |si| quantity += si.quantity }

Can anyone suggest a more succinct method please?


You may count the total quantity for all products using one database query.

class Product < ActiveRecord::Base
  has_many :shops, :through => :stock_items
  has_many :stock_items
  scope :with_total, :select => '[products].id, [products].name, sum([si].quantity) as total', 
    :joins => "left outer join stock_items [si] on [si].product_id = [products].id",
    :group => "[products].id, [products].name"  
end

Now you can get the total with this:

Product.with_total.first.total


Product.first.stock_items.count
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜