views:

50

answers:

1

For example I have a comments models, and I have a post model, but comments can comment on other comments.

So it seems I need a join table I'll call commentables. To create this, do I really need to create a commentable table with a post_id and a comment_id ?

Or can I do something like this without one :

has_many            :comments,
                    :through => :commentables,
                    :source => :post

Not really sure what's the best way to accomplish this. I'm a huge newbie.

+5  A: 

No, you shouldn't need a join table in this case. Join tables are for has_and_belongs_to_many relationships, and in this case, you don't need to have one of those (comments can't belong to many posts, can they?).

You've got two options to go about this. The first is to create a polymorphic relationship:

class Post < ActiveRecord::Base
  has_many :comments, :as => :parent
end

class Comment < ActiveRecord::Base
  belongs_to :parent, :polymorphic => true
  has_many   :children, :class_name => 'Comment', :as => :parent # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Child' model
end

This will allow a comment to either belong to a post, or another comment. Comment.last.parent will return either a Post or a Comment record.

The second option is to make all comments belong to a specific post, but have their own parent-child relationship:

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :parent, :class_name => 'Comment'   # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Parent' model
  has_many   :children, :class_name => 'Comment' # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Child' model
end

This way, your comments will always belong to a post, as well as the potential to belong to another comment.

If you're planning to nest comments (at least more than one level), I would suggest the second option. This would allow you to fetch all comments for a specific post in one query (instead of having to find children for each comment), and you could sort the comments in the application before rendering them. But either way should work.

vonconrad
Great answer. +1
Dave Sims
Wow! I can't thank you enough for this! Thank you so much
Trip
You're welcome. :)
vonconrad
Hey Vonconrad, I was curious if you knew how to set up for the form for this as well? I've been trying to work around this here at : http://stackoverflow.com/questions/3938173/how-do-you-make-a-form-out-of-a-polymorophic-table
Trip