加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – has_many:通过多态关系

发布时间:2020-12-17 02:27:42 所属栏目:百科 来源:网络整理
导读:我使用rails3并尝试构建一些复杂的关联. 我有产品,版本和属性模型. class Version ActiveRecord::Base belongs_to :product has_many :specs has_many :properties,:through = :specsendclass Product ActiveRecord::Base has_many :versions has_many :spec
我使用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 =>真正.你能帮助我吗?

解决方法

怎么样:

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,: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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读