Rails基于通过关系存在的集合查找

时间:2013-11-18 18:37:43

标签: ruby-on-rails activerecord

我正在尝试根据包含集合的实例的关系选择实例。简化示例如下:

class Product::Variation < ActiveRecord::Base
  attr_accessible :name, :product_id, :quantity

  belongs_to :product
  has_many :bids, :foreign_key => :product_variation_id
  has_many :product_variation_property_values, :class_name => 'Product::Variation::PropertyValue'
  has_many :property_values, :through => :product_variation_property_values, :class_name => 'Property::Value'
end

class Product::Variation::PropertyValue < ActiveRecord::Base
  attr_accessible :property_value_id, :variation_id, :property_id

  belongs_to :variation
  belongs_to :property_value, :class_name => 'Property::Value'
end

class Property < ActiveRecord::Base
  attr_accessible :name

  has_many :values, :class_name => 'Property::Value'
end

class Property::Value < ActiveRecord::Base
  attr_accessible :content

  belongs_to :property
  belongs_to :partner
end

所以现在我想做类似下面的事情(在伪代码中):

Variation.where(:property_values includes [Property::Value.find(1), Property::Value.find(2)])

有没有办法使用ActiveRecord执行此操作?

如果您需要更多信息,请与我们联系。

更多信息

我尝试了以下内容:

Product::Variation.joins(:property_values).where('property_values.id' => [Property::Value.find(1).id, Property::Value.find(2).id]).first

...这是以下SQL ...

SELECT "product_variations".* FROM "product_variations" INNER JOIN "product_variation_property_values" ON "product_variation_property_values"."variation_id" = "product_variations"."id" INNER JOIN "property_values" ON "property_values"."id" = "product_variation_property_values"."property_value_id" WHERE "property_values"."id" IN (1, 2)

......这会返回......

#<Product::Variation id: 25, product_id: 1, quantity: 39, created_at: "2013-11-18 00:18:45", updated_at: "2013-11-18 00:18:45">

但如果我这样做:

Product::Variation.find(25).property_values.inspect

......我明白了......

[#<Property::Value id: 1, property_id: 1, content: "XS", created_at: "2013-11-18 00:18:45", updated_at: "2013-11-18 00:18:45", color: nil, color_texture: nil, secondary_color: nil>, #<Property::Value id: 6, property_id: 2, content: "Dark Wood", created_at: "2013-11-18 00:18:45", updated_at: "2013-11-18 00:18:45", color: "#855E42", color_texture: "striped", secondary_color: "#FFB90F">]

但我正在寻找包含Product::Variation 1和2的Property::Value。这将返回包含1或2的内容。

1 个答案:

答案 0 :(得分:0)

这应该适用于join查询。很难写出形式的心,但应该是这样的:

Variation.joins(propert_values: :values).where('values.id' => [Property::Value.find(1).id, Property::Value.find(2).id]).first