繁体   English   中英

Rails-渴望加载has_many:通过关联条件

[英]Rails - eager load has_many :through with condition on association

假设我有一个具有has_many :through关联的Item模型和Category模型:

class Item < ActiveRecord::Base
  has_many :category_items
  has_many :categories, through: category_items
end

class Category < ActiveRecord::Base
  has_many :category_items
  has_many :items, through: category_items
end

class CategoryItems < ActiveRecord::Base
  belongs_to :category
  belongs_to :items
end

现在,我希望对项目具有作用域,该作用域将获取特定类别处于特定状态(假设具有状态属性)的所有项目。 例如:获取所有状态为“有货”且属于id = 3的类别的项目,例如: scope :in_stock_for_category, ->(category) { where(status: SOME_ENUMERATED_VALUE) ....我遗漏了查询的最后一部分将结果集限制为特定类别。

谢谢!

由于您的items表中没有category_id列, cateogeries在指定特定类别的ID条件之前,需要在范围中加入category_itemscateogeries

class Item < ActiveRecord::Base
  scope :in_stock_for_category, -> do |category|
    joins(:category_items).
    where(category_items: {category_id: category.id}).
    where(items: {status: SOME_ENUMERATED_VALUE}).
    group("items.id") # grouping might be unnecessary since you're adding the where condition for the category's id
  end
end

那可行。 或者,如果您想加入categories ,请执行以下操作:

class Item < ActiveRecord::Base
  scope :in_stock_for_category, -> do |category|
    joins(:categories).
    where(categories: {id: category.id}).
    where(items: {status: SOME_ENUMERATED_VALUE}).
    group("items.id") # grouping might be unnecessary since you're adding the where condition for the category's id
  end
end

但是,如果您已经有一个category ,则为具有特定状态的项目创建has_many关系可能会很有用。 类似于以下内容:

class Category < ActiveRecord::Base
  has_many :in_stock_items, -> do
    where(items: {status: SOME_ENUMERATED_VALUE})
  end, through: :category_items, source: :item
end

另外,如果您在Item具有状态范围(类似于scope :in_stock, -> { where(status: SOME_ENUMERATED_VALUE) } ),则很有可能将上述has_many关系更改为以下内容:

class Category < ActiveRecord::Base
  has_many :in_stock_items, -> do
    merge(Item.in_stock) # http://apidock.com/rails/ActiveRecord/SpawnMethods/merge
  end, through: :category_items, source: :item
end

那应该把事情整理干净。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM