has_many:通过+多态关系
问题描述:
我使用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。你可以帮我吗?
答
如何:
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)
感谢。它的工作原理,只需要改变可寻址到speccable。没有“belongs_to:spec”,但“belongs_to:property”(它是我的错) – 2010-11-07 00:24:08