我使用rails3并尝试构建一些复杂的关联。
我有产品,版本和属性模型。
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 =&gt;真正。你能救我吗?
答案 0 :(得分: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)