activerecord - 如何找到具有多个“has_many through”关系的项目
问题描述
我有一个使用“has_many through: 关系”实现的多对多关系模型。例如
汽车 has_many :features, 虽然: :feature_associations
我有汽车清单(VIN1、VIN2、VIN3)和功能清单,“4 门”、“6 缸”、“DVD 播放器”、“GPS”、“蓝牙音频”……
每辆车可以有多个特征(通过将它们联系在一起的特征关联)。
现在,我正在尝试搜索具有多种功能的汽车。我想找到同时具有“GPS”和“4 门”功能的汽车。
到目前为止,我找到了一个查询,它可以为我提供具有任何(OR)功能的汽车,但我想要所有功能(AND)
class Feature < ApplicationRecord
has_many :feature_associations
has_many :cars, through: :feature_associations
end
class Car < ApplicationRecord
has_many :feature_associations
has_many :features, through: :feature_associations
end
class FeatureAssociation < ApplicationRecord
belongs_to :feature
belongs_to :car
end
Car.includes(:feature_associations,:features).references(:features).where( features: { name: ["4-door","GPS"] })
以上返回所有具有 4 门或 GPS 的汽车,但我正在寻找所有具有这两种门的汽车。
解决方案
我找到了一种方法,但它不是很“activerecord-y”。
list = []
Car.includes(:feature_associations,:features).references(:features).where( features: { name: "4-door" }).each do |k| list << k.id end
Car.includes(:feature_associations,:features).references(:features).where(id: list).where( features: { name: "GPS" })...
这需要每个选择的特征进行一次查询;所以感觉我本可以做得更糟。另一方面,可能有一种“正确的方法”,我非常怀疑就是这样。
你有更好的方法吗?(请?)
推荐阅读
- sql - PL/SQL:函数返回无值
- bots - 如何将我的 Discord 机器人活动设置为其所在的公会数量?
- java - Java的HttpServer是异步的吗?
- c# - 在实体 context.cs 中维护自定义代码自动创建的代码
- c++ - 读取、写入和 as_bytes 函数
- vuejs2 - Element UI 对话框组件第一次可以打开,第二次打不开
- macos - 在 Mac (Catalina) 上安装 Azure 存储资源管理器不起作用
- qt - 自定义 QQuickPaintedItem 中的渲染质量差
- javascript - 如何在 Javascript 中连接对象和数组?
- python - 如何让我的函数处理异常?