4

我使用rails3並試圖建立一些複雜的關聯。has_many:通過+多態關係

我有產品,版本和屬性模型。

class Version < ActiveRecord::Base 
    belongs_to :product 
    has_many :specs 
    has_many :properties, :through => :specs 
end 

class Product < ActiveRecord::Base 
    has_many :versions 
    has_many :specs 
    has_many :properties, :through => :specs 
end 

class Property < ActiveRecord::Base 
end 

class Spec < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :spec 
    belongs_to :version 
end 

它的工作完美,但我想使用的產品和版本的多態關係,所以表規格將只有spec_id和some_other_id,而不是spec_id,PRODUCT_ID,VERSION_ID。

我不知道我應該放在哪裏:as和where:polymorphic => true。你可以幫我嗎?

回答

4

如何:

class Version < ActiveRecord::Base 
    belongs_to :product 
    has_many :specs, :as => :speccable 
    has_many :properties, :through => :specs 
end 

class Product < ActiveRecord::Base 
    has_many :versions 
    has_many :specs, :as => :speccable 
    has_many :properties, :through => :specs 
end 

class Property < ActiveRecord::Base 
end 

class Spec < ActiveRecord::Base 
    belongs_to :speccable, :polymorphic => true 
    belongs_to :spec 
end 
#table: specs(id,spec_id,speccable_type,speccable_id) 
+0

感謝。它的工作原理,只需要改變可尋址到speccable。沒有「belongs_to:spec」,但「belongs_to:property」(它是我的錯) – 2010-11-07 00:24:08