2012-09-23 109 views
0

Possible Duplicate:
Unable to join self-joins tables in Rails範圍在Rails和嵌套查詢

我多類別

class Category < ActiveRecord::Base 
    belongs_to :parent, :class_name => "Category", :foreign_key => "parent_id" 
    has_many :children, :class_name => "Category" 
    has_many :products 
    attr_accessible :description, :title, :parent 

end 

這裏是Product

class Product < ActiveRecord::Base 
    belongs_to :category 
end 

一個模式,我需要在Product定義範圍,能夠找到所有產品按父類別名稱

class Product < ActiveRecord::Base 
#..... 
#scope :of_tea, lambda{ where(:category.parent.name => "tea") } # not working 
end 
+0

我想你的意思是在指定的外鍵:孩子的關係,而不是:父。 – cdesrosiers

+0

我需要具有某個父類別的所有產品。這是'茶'。例如:'茶/紅茶','茶/水果茶'... –

回答

1

使用哈希指定where條件:

where(:category => { :parents => { :title => "tea" } }) 
+0

沒有。 'Product.of_tea 2012-09-23 19:30:33 DEBUG - Product Load(0.5ms)SELECT'products'。* FROM'products' WHERE'Object'.'name' ='tea' ActiveRecord :: StatementInvalid:Mysql2 :: Error:'where子句'中的未知列'Object.name' –

+0

在類別中,您引用了「標題」列,但在您引用「名稱」列的範圍內。這是問題嗎? – cdesrosiers

+0

這是我的錯。但它不工作'1.9.3p194:001> Product.of_tea 2012-09-23 19:39:14 DEBUG - 產品負載(0.4ms)SELECT'products'。* FROM'products' WHERE Object '。'title' ='tea' ActiveRecord :: StatementInvalid:Mysql2 :: Error:'where clause'中的未知列'Object.title':SELECT'products'。* FROM'products' WHERE Object'.'title '='茶' ' –