【问题标题】:Rails query include not workingRails 查询包括不工作
【发布时间】: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


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    试试这个:

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

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

    【讨论】:

    • 使用includes 的重点是防止N+1 查询。这将执行 N+1 个查询。
    • 那你应该从Item开始。试试这个,Item.joins(:categorizations =&gt; :category).where('categories.parent_id' =&gt; id)
    • 不,你应该使用includes。它没有任何问题。
    • Category.where(:parent_id =&gt; self.id).includes(:categorizations =&gt; :item)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 2014-07-20
    • 2013-03-22
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    相关资源
    最近更新 更多