在我的應用我有如上述定義的模型項目,類別和分類:的Rails:適用,如果條件都模型和協會
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...')
)?
在此先感謝!
這不僅僅是獲得與所選類別的直接子類別相關的項目嗎? – elc
獲取與您正在查找的物品相關聯的類別,並且當您檢查每個類別的物品時,它只會獲得符合條件的物品。 你想得到什麼結果?它不清楚(至少對我來說)這個問題。 – rorra
假設你想檢查all_children中的所有id,如果你創建了一個數組all_children_ids,那麼你可以找到(all_children_ids),這將導致一個有效的'查找xx在'sql中,而不是重複查詢,如果你單獨點擊id。 – elc