0

可能重复:
无法在 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
4

1 回答 1

1

使用哈希指定 where 条件:

where(:category => { :parents => { :title => "tea" } } )
于 2012-09-23T15:27:00.897 回答