首页 > 解决方案 > Rails:如何获取具有相同关联数组的实例

问题描述

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

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

因此 :

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

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

我有以下查询:

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

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

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

标签: ruby-on-railsactiverecord

解决方案


我会做类似的事情:

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

推荐阅读