views:

487

answers:

5

I want to have a comments section in my app that looks like this:

response1
 response1a
 response1b
  response1b1
response2
 response2a
 response2b
 response2c
  response2c1
   response2c1a
    response2c1a1
     response2c1a1
      response2c1a1a
       response2c1a1a1

Assuming I do this by using HTML such as the following:

<div class="comment">
  Response1
  <div class="comment">
    Response1a
    <div class="comment">
      Response1a1
    </div>
  </div>
  <div class="comment">
    Response1b
  </div>
</div>

And this CSS:

.comment { margin-left: 50px; }

There still remains the question of the data structure to use in Rails to represent the comments and their relationships to each other. Is there native support in Ruby for representing a tree data structure that would work well for this structure of data? Or would I need to build something customized to this task?

+2  A: 
class Post < ActiveRecord::Base
  belongs_to :parent, :class_name => 'Post'
end

migration:

create_table :posts do |t|
  t.string :body
  t.integer :parent_id
end
Joe Van Dyk
+3  A: 

You might want to look in to acts_as_tree for something like this.

Eifion
awesome_nested_set is superior. It all starts with a [good schema for hierarchical data](http://dev.mysql.com/tech-resources/articles/hierarchical-data.html).
macek
+4  A: 

You could use one of the nested set plugins - awesome_nested_set appears to be the one most actively maintained. These allow you to select a full set (including all descendants) with a single call to the database.

Greg Campbell
I've edited it to fix the link - not sure why it didn't work in the first place.
Greg Campbell
+1  A: 

I've had to implement things like this in Rails. It isn't too difficult. Joe's suggestion pretty much covers it. Your case is especially easy because you don't have to worry about moving branches of your tree around. Once a response is added to the tree of responses, it stays where it is or (maybe) gets deleted.

I'd say for a situation like this, implementing it yourself would be more practical than using a gem or plugin.

Ethan
+2  A: 

Hi, You can try to use acts_as_commentable_with_threading plugin - it uses ideas of Ryan Bates (see RailsCast about Polymorphic Associations) and awesome_nested_set

Alexey Poimtsev
Nice this definitely looks the best!
Brian Armstrong