ActiveRecord 获取具有一组特定相关模型的所有模型(AND 不是 OR)
ActiveRecord get all models with a specific set of related models (AND not 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
我现在想要获得所有具有一组特定功能的汽车。例如,我想获取所有具有标识符 "seat-heating" 和 "led-lights" 特征的汽车(但它也可能具有其他特征)。
我尝试了以下查询,但这给了我至少具有其中一项功能的所有汽车,而不是所有功能(因为它会导致 SQL "IN" 查询) :
scope :by_key_features, ->(identifiers) { joins(:key_features).where(key_features: { identifier: identifiers }).group('cars.id') }
如有任何帮助,我们将不胜感激!
您的查询将 select 所有具有至少一项匹配特征的汽车。因此,您只需要 select 具有与查询中相同数量的所有特征的汽车。
scope :by_key_features, ->(identifiers) {
joins(:key_features)
.where(key_features: { identifier: identifiers })
.group('cars.id')
.having('COUNT(key_features.id) >= ?', identifiers.size)
}
我有一个汽车数据库,这些汽车具有特定的功能(如座椅加热、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
我现在想要获得所有具有一组特定功能的汽车。例如,我想获取所有具有标识符 "seat-heating" 和 "led-lights" 特征的汽车(但它也可能具有其他特征)。
我尝试了以下查询,但这给了我至少具有其中一项功能的所有汽车,而不是所有功能(因为它会导致 SQL "IN" 查询) :
scope :by_key_features, ->(identifiers) { joins(:key_features).where(key_features: { identifier: identifiers }).group('cars.id') }
如有任何帮助,我们将不胜感激!
您的查询将 select 所有具有至少一项匹配特征的汽车。因此,您只需要 select 具有与查询中相同数量的所有特征的汽车。
scope :by_key_features, ->(identifiers) {
joins(:key_features)
.where(key_features: { identifier: identifiers })
.group('cars.id')
.having('COUNT(key_features.id) >= ?', identifiers.size)
}