首页 > 解决方案 > 如何找到具有多个“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 的汽车,但我正在寻找所有具有这两种门的汽车。

标签: activerecordruby-on-rails-5

解决方案


我找到了一种方法,但它不是很“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" })...

这需要每个选择的特征进行一次查询;所以感觉我本可以做得更糟。另一方面,可能有一种“正确的方法”,我非常怀疑就是这样。

你有更好的方法吗?(请?)


推荐阅读