Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord - Self Referencing Associations

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!

like image 340
Drew Avatar asked Dec 29 '22 14:12

Drew


2 Answers

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.

like image 84
Ron DeVera Avatar answered Jan 05 '23 18:01

Ron DeVera


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.

like image 22
fractious Avatar answered Jan 05 '23 17:01

fractious