I am looking for some guidance on how to go about implementing comment/reply section for an article. I want users to leave comments for an article. I also want users to reply to comments, but allow more than one reply deep. So basically no replies to replies or nested replies. I have found a gem called closure_tree, but I think this can be done without the need for a gem.
Currently I am showing all Comments on the the Article show page. What I want to do is also have the Comments show all Replies on the Article show page. Not sure how to accomplish this.
|--Article |--Comment |--Reply |--Reply |--Reply |--Comment |--Reply
Thank you for any guidance you can offer.
That's a great question. I thought I had included some recipes for Comments in the book, but I alas I guess it doesn't.
You can definitely do this without a gem.
Start by adding a parent_id column on the Comments table. Then on the comment model, something like this:
belongs_to :parent, class_name: 'Comment', optional: true has_many :replies, class_name: 'Comment', foreign_key: :parent_id, dependent: :destroy
With this setup you can do @comment.replies, and it will pull in all replies for the comment. They are all in one table keeping things nice and tidy. From there you can really go infinite layers deep, but you'll run into U.I challenges with that.
Here's a tweet that helps with visualizing:
Does all of that make sense?
Okay great! It does make sense, and will try to implement. Thank you!
I was able to get it working based on your feedback. Thank you. I will try to write a blog, because I am sure I will run into this again. :D
Great little tutorial James!!! You can definitely link to the site I appreciate that!