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.