简体   繁体   中英

Double Polymorphic Association in Rails

I have a join table and I would like both the belongs_to associations to be polymorphic. 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. What I'm trying to achieve is a flexible design which allows me to create new Taggables or TagGroups without creating new join tables. For instance, without the double polymorphic, Taggable1 would need a Taggable1Taggings table to join Taggable1 with the polymorphic TagGroups. Likewise, I would need Taggable2Taggings, Taggable3Taggings, Taggable4Taggings, etc etc.

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:

https://github.com/fauna/has_many_polymorphs

this fork claims to be compatible with Rails 3:

https://github.com/jystewart/has_many_polymorphs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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