加入两个协会

时间:2018-06-13 08:31:32

标签: ruby-on-rails activerecord

我有4个模型:CatalogProductValueCharacteristic。 目录有很多产品,产品有很多价值,价值属于特征,属于产品。

因此:

  • 产品有catalog_id

  • 值为product_idcharacteristic_id

  • 一个特征是没有任何外键链接到这些模型

  • 一个特征有很多值

我想找到属于目录的给定产品系列的值的特征,而不加载所有产品和所有值。

我能做什么但看起来非常低效:

@products = Product.where(catalog_id: @catalog.id)
@characteristics = Value.distinct.where(value_id: @products.pluck(:id)).pluck(:characteristic_id)

这是我尝试过的:

Characteristic.joins(value: :product).where(values:{products:{catalog_id: @catalog.id}})

但是我收到了这个错误:

Can't join 'Characteristic' to association named 'value'; perhaps you misspelled it?

我在哪里错过了什么?

1 个答案:

答案 0 :(得分:0)

根据您在问题中所写的内容,Characteristic模型与has_manyValue的关联相关联。所以你可以这样加入:

Characteristic.joins(values: :product).where(products: { catalog_id: @catalog.id })

请注意,您不应在products子句中嵌套where,因为它是products表上的“常规”条件。