2011-08-31 3 views
1

Shop 모델과 Product 모델이 있습니다. 또한 StockItem에는 StockItem 모델이 있으며 두 모델을 합치는 모델은 shop_id, product_idquantity입니다.모든 상점에서 제품의 총 재고 보유량 찾기

나는 모든 상점에서 재고 각 제품의 총 수량과 내가 지금이 일을하고있어 방법을 찾을 필요가 어설픈 조금 느낌 :

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

사람이 더 간결 방법을 제안 할 수 있습니다 부디?

답변

1

하나의 데이터베이스 쿼리를 사용하여 모든 제품의 총 수량을 계산할 수 있습니다.

Product.with_total.first.total 
+0

이것은 잘 작동하고 훨씬 더 효율적으로 보입니다. 감사! – Simon

1
Product.first.stock_items.count 
+0

이 아주없는 내가 무엇을 찾고 있었다 - 그것은 양 하나 하나가 아닌 제품을 운반 상점의 수를 반환합니다

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 

지금 당신이 가진 총을 얻을 수 있습니다 주식이있다. – Simon