2014-01-25 33 views
0

有沒有一種方法可以獲得客戶訂購特定產品的結果?我有我的模型設置是這樣的:在Rails中找到客戶訂購的產品

class Customer < ActiveRecord::Base 
has_many :order_items 
has_many :products, :through => :order_items 
end 

class OrderItem < ActiveRecord::Base 
belongs_to :product 
belongs_to :customer 
end 

class Product < ActiveRecord::Base 
has_many :order_items 
has_many :customers, :through => :order_items 
belongs_to :category 
end 

理想情況下,我想能夠寫在紅寶石的東西,會回到什麼回報客戶的陣列已經訂購了某種產品。基本上,我想要寫的東西,如:

Customer.product.where(:name => "Widget").first 

而且有工作,並在已下令該產品數據庫返回的第一個客戶。基本上搜索產品表的名稱字段,返回一個product_id,然後使用該product_id查看order_items表中的哪些customer_id與它關聯,並使用這些customer_id返回與這些customer_id相關聯的customers表中的字段

+0

你想要一個客戶,或所有已訂購產品的客戶嗎? –

回答

0

應該工作(未經測試壽)在OrderProduct

OrderProduct.joins(:product).where("products.name = ?", "Widget").map(&:customer_id)  
+0

糾錯:Customer.includes(:products).where('products.name =?','Widget')。map(&:id)。但這是一個緩慢的查詢。 – emrahbasman

+0

更好:Customer.joins(:products).where('products.name =?','Widget')。map(&:id) – emrahbasman

+0

true。不確定查詢的性能含義。 OP將需要實際檢查創建的查詢。 –

1

搜索210 Rails協會很豐富,您必須能夠做到Product.find_by_name(「widget」)客戶,以返回訂購該產品的所有客戶。如果您想要第一位客戶,請致電.first。 (從手機輸入,所以沒有適當的縮進)

1

Customer.include(:products).where('product.name = ?', 'Widget').first

+0

是的,這似乎是正確的方法去實現它 –

+0

其實,真正正確的方法是在產品類中調用方法,名爲ordered_customers(name),並將「小部件」傳遞給它。去OOPS! – beck03076

相關問題