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.
No, you shouldn’t need a join table in this case. Join tables are for
has_and_belongs_to_manyrelationships, 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:
This will allow a comment to either belong to a post, or another comment.
Comment.last.parentwill return either aPostor aCommentrecord.The second option is to make all comments belong to a specific post, but have their own parent-child relationship:
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.