has_many:通过+多态关系 [英] has_many :through + polymorphic relationships

查看:115
本文介绍了has_many:通过+多态关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用rails3并尝试建立一些复杂的关联.

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

它的工作原理很完美,但是我想使用产品和版本作为多态关系,因此表规范将仅具有spec_id和some_other_id,而不是spec_id,product_id,version_id.

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.

我不知道我应该把:as和:polymorphic =>放在哪里.你能帮我吗?

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

推荐答案

怎么样:

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)

这篇关于has_many:通过+多态关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆