title: How to properly render nested comments in rails?
body: <p>I'm trying to make nested comments work properly in a rails 5 app and running into a lot of difficulty.</p>
  
  <p>I'm building a question and answer site, and I have an Acomment model in which there are comments that belong to answers, and then there are comments that belong to other comments:</p>
  
  <pre><code>class Acomment &lt; ApplicationRecord
    belongs_to :answer
    belongs_to :user
    belongs_to :parent, class_name: "Acomment", optional: true
    has_many :replies,
             class_name: "Acomment", foreign_key: :parent_id, dependent: :destroy
  end
  </code></pre>
  
  <p>I want to display all comments, and then all replies to comments, and replies to replies, etc.  But I can't figure out how to make the nesting work properly.</p>
  
  <p>In my view, inside an each loop, I'm rendering the <code>_comment.html.erb</code> partial:</p>
  
  <pre><code>&lt;% answer.acomments.each do |comment| %&gt;
    &lt;%= render :partial=&gt;"comment", :object=&gt;comment %&gt;
  &lt;% end %&gt;
  </code></pre>
  
  <p>Then, inside my <code>_comment.html.erb</code> partial, I'm displaying the comments, a reply link, and then rendering a partial for the replies to comments:</p>
  
  <pre><code>&lt;div&gt;
    &lt;%= comment.body %&gt;
    &lt;%= link_to "Reply", new_acomment_path(:parent_id =&gt; comment, :answer_id =&gt; comment.answer) if comment.parent_id.blank? %&gt;
  
    &lt;%= render partial: "reply", collection: comment.replies %&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>Here's the <code>_reply.html.erb</code> partial:</p>
  
  <pre><code>&lt;%= reply.body %&gt;
  &lt;%= link_to "Reply", new_acomment_path(:parent_id =&gt; reply, :answer_id =&gt; reply.answer) %&gt;
  </code></pre>
  
  <p>I'm running into two problems:</p>
  
  <p>1) When I render the first partial, not only does it render the comments, but it also renders the replies at the same time (since they are also comments).</p>
  
  <p>2) When I render the second partial (the replies), they are not nested within the comments where they are supposed to.  Everything is out of order.</p>
  
  <p>EDIT:
  I expect to see this: </p>
  
  <pre><code>Comment 1 
    Comment on Comment 1 
      Comment on Comment on Comment 1 
  Comment 2 
  </code></pre>
  
  <p>But instead this is what I'm seeing: </p>
  
  <pre><code>Comment 1 
  Comment on Comment 1 
  Comment 2 
  Comment on Comment 1 
  Comment on Comment on Comment 1 
  Comment on Comment on Comment 1
  </code></pre>
  
  <p>Any help would be greatly appreciated.</p>