Rails: How do self-referential has_many models work?

Andrew picture Andrew · Feb 24, 2011 · Viewed 19.6k times · Source

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!

Answer

Wizard of Ogz picture Wizard of Ogz · Feb 24, 2011

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"