ruby-on-railsroutesacts-as-tree

Is it possible to have file-system-like routes with acts_as_tree?


I have a Folder model which acts_as_tree.

Is it possible that the routes represent the folder structure?

Folders:

1: Folder A
  2: Folder B
  3: Folder C
    4: Folder D
5: Folder E

Routes:

/folders/1
/folders/1/2
/folders/1/3/4
/folders/1/2/new
/folders/...

Is this possible?


Solution

  • So far as I can tell, there's no easy way to do this.

    I think the best way to do this is with a set of named routes.

    I haven't tested this, so there's no guarantees, but it should give you some hints even if it fails.

    map.my_new_folder '/folders/:ancestors/:id/new', :controller => "folders",
     :action => "new", :ancestors => /^(\d+\/?)*$/
    map.my_show_folder, '/folders/:ancestors/:id', :controller => "folders",
     :action => "show", :ancestors => /^(\d+\/?)*$/
    map.my_edit_folder '/folders/:ancestors/:id/edit', :controller => "folders",
     :action => "edit", :ancestors => /^(\d+\/?)*$/
    ...
    

    You'll have to form the ancestor string yourself and pass it as an option to my_x_folder_path. But you should get the pretty urls you want. You might be better of extracting it to a helper that can also dynamically select the resource path or the named route path based on the existence of ancestors.