首页 > 解决方案 > ActiveRecord 获取具有一组特定相关模型的所有模型(AND 不是 OR)

问题描述

我有一个汽车数据库,这些汽车具有特定的功能(如座椅加热、LED 灯、交流电……)。

模型设置如下:

class Car < ApplicationRecord
  has_many :car_key_features
  has_many :key_features, through: :car_key_features
end

class CarKeyFeature < ApplicationRecord
  belongs_to :car
  belongs_to :key_feature
end

class KeyFeature < ApplicationRecord
  has_many :car_key_features
  has_many :cars, through: :car_key_features
end

我现在想获得所有具有特定功能的汽车。例如,我想获得所有具有标识符“座椅加热”和“led-lights”功能的汽车(但它也可能具有附加功能)。

我使用以下查询进行了尝试,但这为我提供了至少具有其中一项功能的所有汽车,而不是所有汽车(因为它会导致 SQL“IN”查询):

scope :by_key_features, ->(identifiers) { joins(:key_features).where(key_features: { identifier: identifiers }).group('cars.id') }

对此的任何帮助将不胜感激!

标签: ruby-on-railsrubyactiverecordruby-on-rails-6

解决方案


您的查询将选择至少具有一项匹配功能的所有汽车。因此,您只需要选择与查询中所有特征数量相同的汽车。

scope :by_key_features, ->(identifiers) {
  joins(:key_features)
    .where(key_features: { identifier: identifiers })
    .group('cars.id')
    .having('COUNT(key_features.id) >= ?', identifiers.size) 
}

推荐阅读