【发布时间】:2013-04-01 08:37:51
【问题描述】:
在我的应用中,我有 3 个模型:Item、Category 和 Categorization 定义如下:
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)
不会将与该类别关联的项目返回给我。我在这里错过了什么?
【问题讨论】:
-
“不会将与该类别关联的项目返回给我”到底是什么意思?您预计会发生什么以及会发生什么?
-
我期待我可以访问 where 获得的类别中的 :items,但 :items 是空的。
-
当使用
includes时,您可能会得到空的items。如果您只想检索包含项目的类别,则必须使用joins,它会进行内部连接。 -
@Rui 你解决了吗?
标签: ruby-on-rails ruby associations