Skip to main content

How do I implement nested comments

Rails • Asked by TL
I'm looking for a tutorial on how to implement nested comments in my project. The requirements are that the comments must be editable and deletable by owner as well. As a plus, we plan on using `act_as_votable` to make them votable, and have [+] and [-] signs to make them collapsible.

I was thinking in using Vue.js for this, since having a lot of comments and nested comments would implicate in having hundreds of unnecessary Rails forms (if we used plain Rails for that). 

Anyone know of a good tutorial on how to achieve this? If not, Chris, can you consider this as an episode request?

You can watch this: `https://gorails.com/episodes/reposting-retweeting-reblogging?autoplay=1`. Either you do the self referencing as it is shown in the video or you can do comments and comment_replies. In the following example Comment is polymorphic.

class Post < ActiveRecord::Base
  has_many :comments, as: :commentable, dependent: :destroy
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
  has_many :comment_replies, dependent: :destroy
end

class CommentReply < ActiveRecord::Base
  belongs_to :comment, touch: true
end

Sure, it's better with React or Vue as with jQuery this can get pretty messy.

You can use act as votable but it might be an overkill and I am not sure how it works with FE frameworks but shouldn't make a difference. It's just a many to many on User and Comment. If you wanna wanna vote on sth else too then just make it polymorphic like the example above (The comment is polymorphic here but the idea is the same).

There is no magic behind this. You just have to set the foreign keys properly with the request params.

Btw. Chris made a bunch of episodes on this. You should look for them and watch them.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.