Rails ActiveRecord 两次加入同一个表

yiv*_*ivo 5 mysql activerecord ruby-on-rails

我有表连接问题。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
Run Code Online (Sandbox Code Playgroud)

所以我想加入属性和值。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`
Run Code Online (Sandbox Code Playgroud)

有两个相同的表联接characteristics
我怎样才能避免这种情况?

Edm*_*Lee 1

我正在寻找更优雅的解决方案并偶然发现了这一点。但这是可行的,只是不像我想要的那样 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`')
Run Code Online (Sandbox Code Playgroud)