views:

226

answers:

2

I'm a total Ruby/Rails/AR noob. I have a very basic sort of database schema that I can't seem to figure out the best way to represent in the Rails Way.

Table     Post
String    title, author
Text      content
Timestamp posted
Post      parent

The idea here is that top level posts will have parent that is NULL. Every response will have one parent, such that they form natural threads.

The title, author, content and posted I'm not having problems with but the parent bit is tripping me up. Any help, hints or suggestions would be great!

+2  A: 

Your Post model should declare this near the top:

belongs_to :parent, :class_name => 'Post'

Then, using a migration, update your posts table so that each row can track its parent:

add_column :posts, :parent_id, :integer

Now, when you have a Post object called @post, you can reference its parent with @post.parent.

Ron DeVera
Would it be as simple as has_many :replies, :classe_name => 'Post' for the other half of the one-to-many?
Drew
+1  A: 

Take a look at the act_as_tree plugin, it provides a bunch of methods that manage the relationships for you. Railscasts has a screencast on Tree Based Navigation that's worth watching.

fractious
Also, instead of using a field called `posted` if you call it `created_at` rails will automatically populate it with the current time when the record is first saved.
fractious
This saved me a lot of work (unfortunately/fortunately, learning more about ActiveRecord will have to wait)
Drew