j

Comment and reply

James Garcia(jamesgarcia)

Hi Nick,

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.

James

  • Nick Haskins replied
    Solution

    Hey James!

    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:

    https://twitter.com/nphaskins/status/1255619112362893312

    Does all of that make sense?

    Nick

  • j
    James Garcia(jamesgarcia) replied

    Okay great! It does make sense, and will try to implement. Thank you!

  • j
    James Garcia(jamesgarcia) replied

    Hi Nick,

    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

  • j
    James Garcia(jamesgarcia) replied

    Hi Nick,

    Just wrote my blog. Before I publish the blog I wanted to get permission to link to your book. Here is a link to the preview.


  • Nick Haskins replied

    Great little tutorial James!!! You can definitely link to the site I appreciate that!