Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested comments from scratch

Let's say I have a comment model:

class Comment < ActiveRecord::Base
    has_many :replies, class: "Comment", foreign_key: "reply_id"
end

I can show a comment instance`s replies in a view like so:

comment.replies do |reply|
   reply.content
end

However, how do I loop through the replies of the reply? And its reply? And its reply ad infitum? I'm feeling we need to make a multidimensional array of the replies via class method and then loop through this array in the view.

I don't want to use a gem, I want to learn

like image 337
Starkers Avatar asked Mar 25 '14 13:03

Starkers


Video Answer


1 Answers

It seems like what you have is one short step away from what you want. You just need to use recursion to call the same code for each reply as you're calling for the original comments. E.g.

<!-- view -->
<div id="comments">
  <%= render partial: "comment", collection: @comments %>
</div>

<!-- _comment partial -->
<div class="comment">
  <p><%= comment.content %></p>
  <%= render partial: "comment", collection: comment.replies %>
</div>

NB: this isn't the most efficient way of doing things. Each time you call comment.replies active record will run another database query. There's definitely room for improvement but that's the basic idea anyway.

like image 56
jeanaux Avatar answered Oct 14 '22 06:10

jeanaux