mysql - Rails ActiveRecord两次连接同一表

我在表联接方面遇到问题。 ActiveRecord生成将两次连接同一表的SQL。假设我们有以下模型:

class Product < ActiveRecord::Base
  has_many :characteristics
  has_many :properties, through: :characteristics
  has_many :values, through: :characteristics
end

class Value < ActiveRecord::Base
  has_many :characteristics
end

class Property < ActiveRecord::Base
  has_many :characteristics
end

class Characteristic < ActiveRecord::Base
  belongs_to :product
  belongs_to :property
  belongs_to :value
end

所以我想同时加入属性和值。 Product.joins(:properties).joins(:values)将产生下一个SQL:
SELECT `products`.*
FROM `products`
INNER JOIN `characteristics` ON `characteristics`.`product_id` = `products`.`id`
INNER JOIN `properties` ON `properties`.`id` = `characteristics`.`property_id`
INNER JOIN `characteristics` `characteristics_products_join` ON `characteristics_products_join`.`product_id` = `products`.`id`
INNER JOIN `values` ON `values`.`id` = `characteristics_products_join`.`value_id`

characteristics有两个相同的联接。
如何避免这种情况?

最佳答案

我在寻找一种更优雅的解决方案,却无意间发现了这一点。但这会起作用,只是不像我想要的Rails-y那样。

Product.joins(characteristics: :properties)
       .joins('INNER JOIN `characteristics` `characteristics_products_join` ON `characteristics_products_join`.`product_id` = `products`.`id`')
       .joins('INNER JOIN `values` ON `values`.`id` = `characteristics_products_join`.`value_id`')