Forum: Ruby on Rails using polymorphism for tags

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Patrick A. (Guest)
on 2007-05-03 02:28
(Received via mailing list)
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
Eden L. (Guest)
on 2007-05-03 06:26
(Received via mailing list)
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
Patrick A. (Guest)
on 2007-05-03 16:20
(Received via mailing list)
ok thanx, I think I'll stay with the first simple polymorphism solution.
This topic is locked and can not be replied to.