简体   繁体   English

Rails中的双重多态关联

[英]Double Polymorphic Association in Rails

I have a join table and I would like both the belongs_to associations to be polymorphic. 我有一个联接表,我希望两个belongs_to关联都具有多态性。 The relationship would look as follows: 关系如下所示:

双多态

The class structure would look as follows: 类结构如下所示:

Class Tagable1 < ActiveRecord::Base
  has_many :taggings
  has_many :tag_group_1s, :through => :taggings
  has_many :tag_group_2s, :through => :taggings
  ...
end

Class TagGroup1 < ActiveRecord::Base
  has_many :taggings
  has_many :taggable_1s, :through => :taggings
  has_many :taggable_2s, :through => :taggings
  ...
end

Class Tagging < ActiveRecord::Base
  belongs_to :taggable, :polymorphic => true
  belongs_to :tag, :polymorphic => true
end

There's obvious drawbacks to this approach, especially the heavy load on the Taggings table. 这种方法有明显的缺点,特别是Taggings表上的负担很重。 What I'm trying to achieve is a flexible design which allows me to create new Taggables or TagGroups without creating new join tables. 我要实现的是一种灵活的设计,它允许我创建新的Taggable或TagGroup,而无需创建新的联接表。 For instance, without the double polymorphic, Taggable1 would need a Taggable1Taggings table to join Taggable1 with the polymorphic TagGroups. 例如,如果没有双重多态性,Taggable1将需要一个Taggable1Taggings表来将Taggable1与多态性TagGroups连接起来。 Likewise, I would need Taggable2Taggings, Taggable3Taggings, Taggable4Taggings, etc etc. 同样,我将需要Taggable2Taggings,Taggable3Taggings,Taggable4Taggings等。

I would love to be enlightened if there are drawbacks I'm not thinking of. 如果有我没有想到的缺点,我很乐意得到启发。

I'm not sure if it's Rails 3 compatible, but you want the has_many_polymorphs gem: 我不确定它是否与Rails 3兼容,但是您需要has_many_polymorphs gem:

https://github.com/fauna/has_many_polymorphs https://github.com/fauna/has_many_polymorphs

this fork claims to be compatible with Rails 3: 该货叉声称与Rails 3兼容:

https://github.com/jystewart/has_many_polymorphs https://github.com/jystewart/has_many_polymorphs

看起来像是可标记的宝石可以使您的生活更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM