2
我有表連接問題。 ActiveRecord生成兩次連接同一個表的SQL。假設我們有模型:Rails ActiveRecord加入同一個表兩次
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
。我怎樣才能避免這種情況?
對不起,我的英語
謝謝
你試過了:'Product.joins(特性:[:property,:value])'? – BroiSatse 2015-01-26 23:55:45
謝謝。有用。但是,如果我有'has_many:a','has_many:b,throught::a','has_many:c,throught::b'這樣的多個關聯關係,它將無法工作。 – yivo 2015-01-27 00:27:18