在我的应用程序中,我有如上定义的模型项目、类别和分类:
class Item < ActiveRecord::Base
attr_accessible :name, :description, :property_valuations, :barcode
has_many :categorizations
has_many :categories, :through => :categorizations
end
class Category < ActiveRecord::Base
attr_accessible :name, :description, :parent, :children, :items, :parent_id
has_many :children, :class_name => "Category", :foreign_key => "parent_id", :dependent => :nullify
belongs_to :parent, :class_name => "Category"
has_many :categorizations
has_many :items, :through => :categorizations
def all_children(children_array = [])
children = Category.where(:parent_id => self.id).includes(:items)
children_array += children.all
children.each do |child|
children_array = child.all_children(children_array)
end
children_array
end
end
class Categorization < ActiveRecord::Base
attr_accessible :category, :item
belongs_to :category
belongs_to :item
end
我正在递归搜索类别树以查找与类别关联的项目。但是,除了按 parent_id 过滤类别之外,我还想应用过滤器项目名称。我该怎么做(我期待类似的东西Category.where(:parent_id => self.id).includes(:items).where(:name => 'something...')
)?
提前致谢!