# Using polymorphism for tags

**URL:** <https://www.ruby-forum.com/t/using-polymorphism-for-tags/103213>\
**Category:** Rails\
**Created:** [May 3, 2007, 12:28am UTC](https://www.ruby-forum.com/t/using-polymorphism-for-tags/103213 "2007-05-03T00:28:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![patcito](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/50afbb/32.png) [@patcito](https://www.ruby-forum.com/u/patcito)\
**Post date:** [May 3, 2007, 12:28am UTC](https://www.ruby-forum.com/t/using-polymorphism-for-tags/103213/1 "2007-05-03T00:28:31Z")

</div>

I have something like that:

class Commercial \< ActiveRecord::Base  
belongs\_to :announcer  
has\_many :tags, :as=\> :taggable  
end

class Announcer \< ActiveRecord::Base  
has\_many :commercials  
has\_many :tags, :as=\> :taggable  
end

class Tag \< ActiveRecord::Base  
belongs\_to :taggable, :polymorphic =\> true  
end

with commercials (id,name)  
announcers(id,name)  
tags(id,name,taggable\_id,taggable\_type)

now that’s not very DRY because I have several tags that repeat  
themselves for different taggable\_type.  
is there a better way to deal with that?

thanx in advance

Pat

---

<div class="post-metadata">

**Author:** ![patcito](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/50afbb/32.png) [@patcito](https://www.ruby-forum.com/u/patcito)\
**Post date:** [May 3, 2007, 4:26am UTC](https://www.ruby-forum.com/t/using-polymorphism-for-tags/103213/2 "2007-05-03T04:26:43Z")

</div>

You could turn tags into an intermediate join table on a “tag details”  
class – although after typing it out it looks pretty ugly. You don’t  
save that much unless your name column is going to be huge or unless  
you’re going to store more information per tag (e.g. create date,  
counter caches etc).

Schema:  
tags(id, taggable\_id, taggable\_type)  
tag\_details(tag\_id, name)

class Tag \< ActiveRecord::Base  
belongs\_to :taggable, :polymorphic =\> true  
has\_one :tag\_detail, :dependent =\> :destroy

def name  
tag\_detail.name  
end

def name=(v)  
tag\_detail.name = v  
end

def ensure\_tag\_detail  
create\_tag\_detail  
end  
after\_validation\_on\_create :ensure\_tag\_detail  
end

class TagDetail \< ActiveRecord::Base  
belongs\_to :tag  
end

---

<div class="post-metadata">

**Author:** ![patcito](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/50afbb/32.png) [@patcito](https://www.ruby-forum.com/u/patcito)\
**Post date:** [May 3, 2007, 2:20pm UTC](https://www.ruby-forum.com/t/using-polymorphism-for-tags/103213/3 "2007-05-03T14:20:11Z")

</div>

ok thanx, I think I’ll stay with the first simple polymorphism solution.
