Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to limit comment nesting with Hotwire and Turbo?

Marc Jaramillo asked in Rails

I asked this question in the discussion on the tutorial itself, but there doesn’t seem to be any activity there. I went through the nested comments series, and the last three videos focused on real-time changes using Hotwire and Turbo. In the first part of the series, Chris introduced a way to limit how deeply comments could be nested, but he doesn’t show this feature in the Hotwire version. I'm curious how the nesting depth limit that was implemented with the original version can be adapted for a Hotwire/Turbo app? The two versions seem drastically different from each other, so I’m not sure where to start. I’m still new to Hotwire and Turbo so any guidance would be greatly appreciated.

Reply

If anyone is interested, I figured out what I needed to do. For context: in the first half of the Nested Comment Threads in Rails series, Chris introduces two local variables inside the comments/_comment.html.erb partial called nesting and max_nesting. He also creates a helper method called reply_to_comment_id(comment, nesting, max_nesting) that sets the parent_id of the reply comment. I couldn't get this approach to work with Hotwire and Turbo, but thanks to a comment by Jay Killeen on Nested Comment Threads in Rails - Part 3 I was able to get this working:

Create a migration to add nesting to comments:

class AddNestingToComments < ActiveRecord::Migration[6.1]
  def change
    add_column :comments, :nesting, :integer
  end
end

Add this inside the Comment model:

  def set_nesting
    if self.parent.present? && self.parent.nesting.present?
      self.nesting = self.parent.nesting + 1
    else
      self.nesting = 1
    end
  end

  def self.max_nesting
    2
  end

Make this change inside the Commentable concern:

def create
    ...
    ...
    if @parent&.nesting.blank? || @parent&.nesting < Comment.max_nesting
      @comment.parent_id = @parent&.id
      @comment.nesting = @comment.set_nesting
    else
      @comment.parent_id = @parent&.parent_id
      @comment.nesting = @comment.set_nesting
    end
    ...
    ...
end

This may not be the best way to handle things, so if anyone has another approach that is better please feel free to comment.

Reply

I have same issue. How can we limit the original version?

Reply
Join the discussion
Create an account Log in

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

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

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