如何查找具有多个“ has_many through”关系的项目

时间:2019-06-06 01:35:18

标签: activerecord ruby-on-rails-5

我有一个使用“ 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的汽车,但我正在寻找所有具有4门或GPS的汽车。

1 个答案:

答案 0 :(得分:0)

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

每个选定功能需要一个查询;所以感觉我可能做得更糟。另一方面,可能存在“正确的方法”,我对此表示高度怀疑。

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