Ruby on rails Rails查询包括不工作

Ruby on rails Rails查询包括不工作,ruby-on-rails,ruby,associations,Ruby On Rails,Ruby,Associations,在我的应用程序中,我有3个模型:项目、类别和分类,定义如下: class Item < ActiveRecord::Base attr_accessible :name, :description has_many :categorizations has_many :categories, :through => :categorizations end class Category < ActiveRecord::Base attr_accessible

在我的应用程序中,我有3个模型:项目、类别和分类,定义如下:

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: id).joins(:items)
Category.where(:parent_id => id).collect(&:items)
试试这个:

Category.where(parent_id: id).joins(:items)
Category.where(:parent_id => id).collect(&:items)
试试这个:

Category.where(parent_id: id).joins(:items)
Category.where(:parent_id => id).collect(&:items)
它将返回与where子句匹配的所有类别的项目。

尝试以下操作:

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

它将返回与where子句匹配的所有类别的项目。

不返回与该类别相关的项目是什么意思。?您希望发生什么以及发生什么?我希望可以访问通过where获得的类别中的:项,但是:项为空。使用include时,您可能会得到空项。如果您只想检索包含项目的类别,则必须使用联接,这是一种内部联接。@您是否已设法解决此问题?不返回与该类别关联的项目是什么意思。?您希望发生什么以及发生什么?我希望可以访问通过where获得的类别中的:项,但是:项为空。使用include时,您可能会得到空项。如果您只想检索包含项目的类别,则必须使用联接,其中有一个内部联接。@您是否已设法解决此问题?使用includes的全部目的是防止N+1查询。这将执行N+1查询。然后您应该从项目开始。试试这个,Item.joins:categorizations=>:category.where'categories.parent\u id=>idNo,您应该只使用includes。Category.where:parent_id=>self.id.includes:categorizations=>:item使用includes的全部目的是防止N+1查询。这将执行N+1查询。然后您应该从项目开始。试试这个,Item.joins:categorizations=>:category.where'categories.parent\u id=>idNo,您应该只使用includes。它没有什么问题。Category.where:parent\u id=>self.id.includes:categorizations=>:item