has_many :through + polymorphic relationships

2019-03-14 03:43发布

I using rails3 and trying to build some complex associations.

I have Product, Version and Property models.

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

It works perfect, but i want to use product and version as polymorphic relations, so table specs will have only spec_id and some_other_id, instead of spec_id, product_id, version_id.

I can't figure out where i should put :as and where :polymorphic => true. Can you help me?

1条回答
放我归山
2楼-- · 2019-03-14 04:36

How about:

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)
查看更多
登录 后发表回答