Ask A Question


You’re not receiving notifications from this thread.

Nested Comments in Rails Part 2, nested comments are showing in reverse order

midtown asked in Rails

I am trying to implement nested comments with max_nested comments as described in this episode:

I'm at approximately the 9 minute mark where nested comments after they reach the max are supposed to fall under the last comment listed. I'm expecting them to be in the order posted, but they are reversed with the most recent showing first instead of at the bottom.


Comments example

This is the code I currently have in _comments.html.erb

<% nesting = local_assigns.fetch(:nesting, 1) %>
<% max_nesting = local_assigns[:max_nesting] %>
<div class='border-left border-bottom border-top p-4 mb-4'>
  <%= %> posted
  <%= simple_format comment.body %>

  <div data-controller='reply'>
      <%= link_to "Reply", "#", data: { action: "click->reply#toggle" } %>
      <%= link_to "Delete", [comment.commentable, comment], method: :delete, data: { confirm: "Are you sure you want to delete this comment?" } if comment.user == current_user %>
    <%= render partial: 'comments/form', locals: {
      commentable: comment.commentable,
      parent_id: (nesting < max_nesting ? : comment.parent_id),
      class: 'mt-4 d-none',
      target: 'reply.form'
    } %>

  <%= render comment.comments, nesting: nesting + 1, max_nesting: local_assigns[:max_nesting] %>


<%= form_with model: [commentable,], html: { class: local_assigns[:class], data: { target: local_assigns[:target] } } do |form| %>
  <div class='form-group'>
    <%= form.text_area :body, placeholder: "Add a comment", class: 'form-control' %>

  <div class='form-group'>
    <%= form.hidden_field :parent_id, value: local_assigns[:parent_id] %>
    <%= form.submit class: 'btn btn-primary' %>
<% end %>

When you <%= render comment.comments, it isn't specifying any order, so you'd want to sort that by created_at if you want them in a particular order. A SQL query doesn't respect any ordering unless you tell it to.

<%= render comment.comments.order(created_at: :asc)


That makes so much sense, it's just odd that I'm following along verbatim and getting different behavior than what shows in the tutorial when demoing the same code.

I also realized that my comments in general were showing up out of order with the newest ones showing at the top, despite having identitical code to the episode. You might consider a similar fix to show expected order in the view:


      <%= render @object.comments.where(parent_id: nil).order(created_at: :asc), max_nesting: 5 %>

Cheers and thanks for this wonderful resource!

Join the discussion
Create an account Log in

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

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

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