12 MarPolymorphic has_and_belongs_to_many
Friday, 12 March 2010 — 16:32We faced today a problem where we needed a polymorphic has_and_belongs_to_many (habtm) implemented on Rails. Let me first explain the problem.
We want to let the user tag content in the site. This content can go from a post, to an image, a video,… sounds like a polymorphic relationship no? :-). One more requirement: we want to have Tags table as a unique list of tags. So a user can tag an image or a video with “cool”, but we will just have one entry in tags table for that word. And of course, same will happen if someone else uses same tag.
If we had just images, that would be a has_and_belongs_to_many case. As we have more than one taggeable object, that’s a polymorphic habtm.
This is how we implemented it, using a middle model class (TagsLinks) which is basically the polymorphic habtm table:
#Post has_many :tag_links, :as => :resource #Image has_many :tag_links, :as => :resource #TagLinks belongs_to :user belongs_to :resource, :polymorphic => true belongs_to :tag #Tag: has_many :tag_links
Ger