Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Using the <a href="http://wiki.rubyonrails.org/rails/pages/ActsAsTree" rel="nofollow noreferrer"><code>acts_as_tree</code></a> plugin should make this fairly easy to implement. Install it using</p> <p><code>ruby script/plugin install acts_as_tree</code></p> <p><code>app/models/comment.rb</code></p> <pre><code>class Comment &lt; ActiveRecord::Base acts_as_tree :order =&gt; 'created_at' end </code></pre> <p><code>db/migrate/20090121025349_create_comments.rb</code></p> <pre><code>class CreateComments &lt; ActiveRecord::Migration def self.up create_table :comments do |t| t.references :parent t.string :title t.text :content ... t.timestamps end end def self.down drop_table :comments end end </code></pre> <p><code>app/views/comments/_comment.html.erb</code></p> <pre><code>&lt;div id="comment_&lt;%= comment.id %&gt;"&gt; &lt;h1&gt;&lt;%= comment.title %&gt;&lt;/h1&gt; &lt;%= comment.content %&gt; &lt;%= render :partial =&gt; 'comments/comment', :collection =&gt; comments.children %&gt; &lt;/div&gt; </code></pre> <p><code>app/views/comments/show.html.erb</code></p> <pre><code>&lt;div id="comments"&gt; &lt;%= render :partial =&gt; 'comments/comment', :object =&gt; Comment.find(params[:id]) %&gt; &lt;/div&gt; </code></pre> <p>The magic happens in <code>show.html.erb</code> when it calls <code>&lt;%= render :partial =&gt; 'comments/comment', :object =&gt; Comment.find(params[:id]) %&gt;</code>, this will cause the partial to recursively render all children comments. If you want a limit to the depth, you can do it in the partial or in the model.</p> <p><strong>Edit:</strong><br /> This will leave you with all the comments with the same spacing in the HTML for every depth. If you want to produce easy to read HTML, just use <code>render(...).gsub(/^/, "\t")</code> this will work recursively as well producing nicely indented HTML.</p> <p>I combined it into my own method in <code>app/helpers/application_helper.rb</code></p> <pre><code>def indented_render(num, *args) render(*args).gsub(/^/, "\t" * num) end </code></pre> <p>So now you can call <code>&lt;%= indented_render 1, :partial =&gt; 'comments/comment', ... %&gt;</code></p> <p><strong>Edit:</strong><br /> Fixed missing closing <code>&lt;/h1&gt;</code> tag in the example.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload