Hi everyone. I’m trying to figure out how to implement site-wide
tagging for my website. I have a rails-based weblog that supports
tagging posts. There’s a has_and_belongs_to_many relationship between
posts and tags. I’d like to now reuse those tags for tagging links as
well. Where I have a posts_tags table with post_id and tag_id fields,
I’d like to add a link_id field. I’d like to use just one table so that
I can easily pull all posts and links associated with a given tag. If I
make a has_and_belongs_to_many relationship between tags and links I
seem to need a links_tags table. How do I make the links/tags
relationship appear in the same table as the posts/tags relationship?
Well, has_many :through sounds like what you need. In order to put
more than just two fields in a many-to-many table, you use has_many
:through.
class Posts < ActiveRecord::Base
has_many :post_tags
has_many :tags, :through => post_tags
end
class Links < ActiveRecord::Base
has_many :post_tags
has_many :tags, :through => post_tags
end
class PostTags < ActiveRecord::Base
belongs_to :posts
belongs_to :links
belongs_to :tags
end
If I were you, I’d make two join tables rather than trying to put it
all into one. It’ll be no more difficult to search by tags, I reckon.
Think of all the null attributes you’ll have in your post_tags table.
That’ll make things difficult.