Ruby on Rails: Routing for a tree hierarchy of places

hierarchical-trees, hierarchy, routes, ruby-on-rails

Solution

Have a look at the Routing Guide for full documentation:

http://guides.rubyonrails.org/routing.html

Specifically section "4.9 Route Globbing".

But I think what you really want to do is declare your route like:

map.connect '/places/*id', :controller => 'places', :action => 'index'

Called with a URL like

/places/foo/bar/1

Yields a params[:id] => ["foo", "bar", "1"]

Which you could easily (re)join with "/" to yield the full string you want "foo/bar/1" (you will probably have to re-insert the leading slash manually.

That should get you going.

Problem

So we've got a legacy system that tracks places with IDs like "Europe/France/Paris", and I'm building a Rails facade to turn this into URLs like http:// foobar/places/Europe/France/Paris. This requirement is not negotiable, the number of possible levels in unlimited, and we can't escape the slashes. Setting up routes.rb for http://foobar/places/Europe is trivial: ``` map.resources :places ``` ...but http:// foobar/places/Europe/France complains "No action responded to Europe". I tried: ``` map.connect '/places/:id', :controller => 'places', :action => 'show' ``` ...but this gives the same result, as apparently the :id ends at the first '/'. How do I make the ID cover anything and everything after the "places"?

Original source