查找具有多对多关系的两个确切实例的记录

时间:2017-02-20 16:07:44

标签: ruby-on-rails postgresql activerecord

我的应用程序具有涉及多种变体的产品的业务逻辑:

class Task < ApplicationRecord
  belongs_to :variant
end

class Variant < ApplicationRecord
  belongs_to :product

  has_many :variant_option_values
  has_many :option_values, through: :variant_option_values
  has_many :prices
end

class Product < ApplicationRecord    
  has_many :product_option_types
  has_many :option_types, through: :product_option_types
  has_many :variants
end

class OptionValue < ApplicationRecord
  belongs_to :option_type
end

class OptionType < ApplicationRecord
  has_many :product_option_types
  has_many :products, through: :product_option_types
  has_many :option_values
end

class ProductOptionType < ApplicationRecord
  belongs_to :product
  belongs_to :option_type
end

class VariantOptionValue < ApplicationRecord
  belongs_to :variant
  belongs_to :option_value
end

ERD看起来像这样: enter image description here

拥有产品product_1如何找到包含OptionValue个实例option_value_1option_value_2option_value_3的变体?请注意,变体必须同时具有所有三个选项值,并且可以具有超过这三个选项值(但不一定)。

1 个答案:

答案 0 :(得分:1)

option_values = [option_value_1, option_value_2, option_value_3]

Variant.include(product: [option_types: :option_values])
  .where("option_values.id IN (?)", option_values.map(&:id))
  .group("products.id")
  .having("count(*) >= ?", option_values.size)