Forum: Ruby on Rails activerecord table help please

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.
C90e2f49c91d6a601f9ccc9e132d211b?d=identicon&s=25 Jeff Larkin (fufish)
on 2006-06-04 06: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.

-Jeff
D5145c421cd25af6fa577c15219add90?d=identicon&s=25 unknown (Guest)
on 2006-06-04 09: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
: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.

Hope this helps,
-Nathan
C90e2f49c91d6a601f9ccc9e132d211b?d=identicon&s=25 Jeff Larkin (fufish)
on 2006-06-04 16:29
Great.  Thanks for the suggestion.
This topic is locked and can not be replied to.