查找所有商店的产品总库存量

时间:2011-08-31 14:17:58

标签: ruby-on-rails ruby ruby-on-rails-3

我有Shop模型和Product模型。我还有StockItem模型加入了两个 - StockItem具有shop_idproduct_idquantity属性。

我需要找到所有商店库存中每种产品的总量,而我现在这样做的方式感觉有点笨拙:

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

有人可以提出更简洁的方法吗?

2 个答案:

答案 0 :(得分:1)

Product.first.stock_items.count

答案 1 :(得分:1)

您可以使用一个数据库查询计算所有产品的总数量。

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

现在你可以得到总数:

Product.with_total.first.total
相关问题