ruby-on-rails - 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 中有这个:
- 类别 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
解决方案
我会做类似的事情:
Product.includes(:categories).select { |p| p.category_ids == [1,3] }
推荐阅读
- docker - Dockerfile Build Error:系统找不到指定的路径
- ios - 无法上传到 App Store Connect 并出现错误“未找到具有 App Store Connect 访问权限的帐户”
- python - 如何使用 HTML 保存 matplotlib 图形以保持动态功能(缩放...)?
- flutter - 为 Flutter 制作多个 Laravel Echo 实例
- python - 如何获得序列模型 Sklearn 的给定预测的概率
- r - 循环输出存储为列表
- html - 如何在全屏视频中显示徽标?
- c# - 在多个子类中覆盖 dispose 方法
- sql - 从组中强制转换的 SQL 查询
- swift - 调用下标 [Swift] 中没有完全匹配