开发者

Finding the total stock amount of a product across all stores

开发者 https://www.devze.com 2023-04-01 18:10 出处:网络
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 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

精彩评论

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