【问题标题】:Rails : how to get the instances having the same array of associationsRails:如何获取具有相同关联数组的实例
【发布时间】:2018-06-14 14:09:22
【问题描述】:

我有两个模型之间的多对多关系,以这种方式链接:

class Product < ApplicationRecord
    has_many :categoriesproducts
    has_many :categories, through: :categoriesproducts
end

class Category < ApplicationRecord
    has_many :categoriesproducts
    has_many :products, through: :categoriesproducts
    has_and_belongs_to_many(:categories,
     :join_table => "category_connections",
     :foreign_key => "category_a_id",
     :association_foreign_key => "category_b_id")
end

class Categoriesproduct < ApplicationRecord
    belongs_to :products
    belongs_to :category
end

因此:

  • 一个产品可以有多个类别
  • 一个类别可以有很多产品
  • 一个类别可以有多个类别

用户可以在表格中查询数据库选择类别。假设我们在数据库中有这个:

  • 类别 1 具有 [类别 3]
  • 类别 2 具有 [类别 3]
  • 产品 A 具有 [类别 1,类别 3]
  • 产品 B 具有 [类别 2,类别 3]

如果用户在我只想获得产品 A 的表单中仅选择类别 1 下的类别 3。

我有以下疑问:

Product.joins(:categories).where(categories: {id: [1,3]})

这给了我所有具有类别 1 或 3 = 产品 A 和产品 B 的产品。

如何获得类别与数组完全匹配的产品?例如,仅具有类别 1 和 3 的那些,在示例中 = 产品 A

【问题讨论】:

  • 如何重构数据库架构?似乎你无法得到想要的结果。例如,您将“parent_category_id”列添加到category 表中。
  • 你是对的。我已经过了几个星期来检查是否有人会知道聪明的 activerecord 查询......但同时我实现了一个 sub_category 模型,它大大简化了我的生活。起初我很懒,但最终意识到几行额外的代码是正确的解决方案。感谢大家的时间。我不确定我是否应该删除这个问题或让它无人回答..
  • 酷!有时简单的代码是件好事..

标签: ruby-on-rails activerecord


【解决方案1】:

我会做类似的事情:

Product.includes(:categories).select { |p| p.category_ids == [1,3] }

【讨论】:

  • 这应该可以,但是效率很低。这可以通过双重连接categories 在数据库中完成,但我不确定如何在 activerecord 中表达。
  • 是的,它确实有效,但我想保留一个 activerecord 对象,因为它与其他查询链接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2021-01-16
  • 2017-07-07
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多