2013-04-01 54 views
2

在我的應用我有3種型號:項目,分類和分類定義如下:Rails的查詢包括不工作

class Item < ActiveRecord::Base 
    attr_accessible :name, :description 

    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 
end 

class Categorization < ActiveRecord::Base 
    attr_accessible :category, :item 

    belongs_to :category 
    belongs_to :item 

end 

但是,這樣做:

Category.where(:parent_id => self.id).includes(:items) 

不會返回我的與類別關聯的項目。我在這裏錯過了什麼?

+1

你是什麼意思,「不會返回與該類別相關的項目」。你期望發生什麼,發生了什麼? – Mischa

+0

我期待着我可以訪問:通過where獲得的類別中的項目,但是:items是空的。 – Rui

+0

使用'includes'時,最終會得到空的'items'。如果您只想檢索包含項目的類別,則必須使用'joins',它進行內部聯接。 – Mischa

回答

0

試試這個:

Category.where(parent_id: id).joins(:items) 
-1

試試這個:

Category.where(:parent_id => id).collect(&:items) 

它將返回where語句匹配所有類別的項目。

+0

使用'includes'的重點在於阻止N + 1個查詢。這將執行N + 1個查詢。 – Mischa

+0

然後你應該從'Item'開始。試試這個,'Item.joins(:categorizations =>:category).where('categories.parent_id'=> id)' – KULKING

+0

不,你應該使用'includes'。沒有什麼問題。 – Mischa