Forum: Ruby on Rails activerecord table help please

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Jeff L. (Guest)
on 2006-06-04 08:00
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?

Thank you for the help.

unknown (Guest)
on 2006-06-04 11:34
(Received via mailing list)
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

class Posts < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, :through => post_tags

class Links < ActiveRecord::Base
  has_many :post_tags
  has_many :tags, :through => post_tags

class PostTags < ActiveRecord::Base
  belongs_to :posts
  belongs_to :links
  belongs_to :tags

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.

Hope this helps,
Jeff L. (Guest)
on 2006-06-04 18:29
Great.  Thanks for the suggestion.
This topic is locked and can not be replied to.