2013-04-02 19 views
1

在我的應用我有如上述定義的模型項目,類別和分類:的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...'))?

在此先感謝!

回答

0

你可以做

Category.where(:parent_id => self.id).includes(:items).where("items.name like ?", '%cheap%') 

這將讓類別,以及符合標準的項目。

即:

categories = Category.where(:parent_id => 2).includes(:items).where("items.name like ?", 'AA%') 
categories.first.items.size # -> 2 
categories.first.id # -> 1 
Category.find(1).items.size # -> 3 
Category.find(1).items.where("name like ?", 'AA%').count # -> 2 

如果你只是想獲得一個父類的子類的物品:

parent_category = Category.find(2) 
Item.joins(:categories).where(categories: {parent_id: parent_category.id}).where("items.name like ?", 'AA%') 
+0

這不僅僅是獲得與所選類別的直接子類別相關的項目嗎? – elc

+0

獲取與您正在查找的物品相關聯的類別,並且當您檢查每個類別的物品時,它只會獲得符合條件的物品。 你想得到什麼結果?它不清楚(至少對我來說)這個問題。 – rorra

+0

假設你想檢查all_children中的所有id,如果你創建了一個數組all_children_ids,那麼你可以找到(all_children_ids),這將導致一個有效的'查找xx在'sql中,而不是重複查詢,如果你單獨點擊id。 – elc

0

遞歸查詢(避免你的all_children的手動遞歸函數)可能會被你的數據庫支持,比如postgres通過with命令,但是rails沒有訪問它的包裝器。如果這種遞歸發生很多,可能值得在這裏做一些閱讀:http://gmarik.info/blog/2012/10/14/recursive-data-structures-with-rails - 它看起來有一些有前途的寶石來解決這個問題,但我沒有親自使用它們中的任何一個。