1

I have a tags model that I'd like to be polymorphic, but I don't want five records for a tag of "video" for example, I want to create the tag once and be able to use it on a variety of models. I've ready some of the questions here about doing that, but I'm not quite getting how to make it work.

So I've got:

class Tag < ActiveRecord::Base
  belongs_to :tagable, :polymorphic => true

end

and

class Post < ActiveRecord::Base
  has_many :tags, :through => :tag_assignments

end

and

class TagAssignment < ActiveRecord::Base
      has_many :tags, :as => :taggable

end

Seems to me that should work, but... reading all the questions here I know I need a :source => option in there somewhere to tie it all together, but I'm just not following exactly how to do it. Can anyone help?

Community
  • 1
  • 1
Slick23
  • 5,827
  • 10
  • 41
  • 72

1 Answers1

5

You have to redo your models as follows:

class Tag < ActiveRecord::Base
  has_many :tag_assignments
end

class TagAssignment < ActiveRecord::Base
  belongs_to :tagable, :polymorphic => true
  belongs_to :tag
end

class Post < ActiveRecord::Base
  has_many :tag_assignments, :as => :tagable
  has_many :tags, :through => :tag_assignments
end

Now given a post you can get its tags as follows:

post.tags

Note

You should consider using the acts-as-taggable-on gem for your use case.

Harish Shetty
  • 64,083
  • 21
  • 152
  • 198