16

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!

Andrew
  • 42,517
  • 51
  • 181
  • 281

1 Answers1

33

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"
Community
  • 1
  • 1
Wizard of Ogz
  • 12,543
  • 2
  • 41
  • 43
  • 1
    I'm fairly certain you don't need the `:foreign_key => "parent_id"` on the belongs_to line. It should only be on the has_many line, yes? – 3nafish Apr 09 '13 at 03:53
  • 1
    If you want to name the child relationship something else, e.g. `children_folders` then you need to specify the class_name: `has_many :children_folders, :foreign_key => "parent_id", :class_name => "Folder"` – AJP Feb 19 '14 at 10:52
  • And what about a mix? like :all_folders how could we do? – Mauro Dias Feb 21 '14 at 14:49