Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I implement nested comments

TL asked in Rails
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?
Reply
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.
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.