Search code examples
ruby-on-railsruby-on-rails-3nested-routesacts-as-tree

Building nested routes for a resource that use acts_as_tree


do you know how to generate dynamically routes such as:

... (/:parent_id(/:parent_id(/:parent_id(/:parent_id))))/:id

I ask this question because I have a Folder model which acts as tree (it have a parent_id field), and its to_param method return its name which is uniq through the scope of the parent_id. So, each :parent_id and event the :id are the name. Here is an example of path (with 4 sub-folders):

/home/desktop/projects/rails/foobar

...where the first :parent_id (the root) is "home" and the :id is "foobar".

Another example of route could be (with 1 sub-folder):

/home/music

...where, as you can see, params[:parent_id] == 'home' and params[:id] == 'music'.

Is there a clean way to write a beautiful Rails 3 route which handle those kind of possible nested routes? Thanks!!


Solution

  • Why don't you just use a route globber and break it up in your controller?

    # routes.rb
    get "/*folders/:id" => "files#show" 
    

    The *folders section will glob up multiple URL segments.

    # files_controller.rb
    def show
      folders = params[:folders].split('/') # gives an array of folder names
      # do whatever else necessary
    end