Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How do self-referential has_many models work?

So, I'm working on an app where I want to users to be able to group objects in "folders". Basically:

User has_many :foos

Foos don't have to be in a folder, but they can be. In that case:

Folder has_many :foos and Foo belongs_to :folder

Now, I'd like to be able to set up folders so they can be nested. I think this is something like...

Folder has_many :folders

I have heard that this kind of self-referential relationship is no big deal, but I don't really get how it works. I haven't been able to figure out how this is supposed to be declared in the model and what columns I need to provide in the database.

Could anyone offer an example? I'd also value any suggestions/heads-up/warnings/lessons learned that you might be able to offer about setting up this kind of relationship in an app.

Thanks!

like image 794
Andrew Avatar asked Feb 24 '11 20:02

Andrew


1 Answers

Checkout coreyward's answer to the question here: Creating a model that has a tree structure

Basically you want to add a "parent_id" field to your folders table and then set up a relationship in your Folder model like this:

belongs_to :parent, :class_name => "Folder"
has_many :folders, :foreign_key => "parent_id"
like image 65
Wizard of Ogz Avatar answered Nov 16 '22 01:11

Wizard of Ogz