2012-09-23 103 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 '='茶' ' –