Ruby on Rails: Routing for a Place Tree Hierarchy

So, we have an outdated system that tracks places with identifiers like "Europe / France / Paris", and I create 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 is unlimited, and we cannot avoid the slash.

Setting up .rb routes 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: id ends with the first "/". How can I make the identifier cover something and everything after the "places"?

+3
source share
2 answers

See the routing guide for full documentation:

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

In particular, the section "4.9 Globe route."

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

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

Called from URL as

/places/foo/bar/1

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

That you can easily (re) join "/" to get the full line you want "foo / bar / 1" (you may have to re-insert the leading slash manually.

That should make you.

+6
source

I tweaked Cody a bit to answer this:

map.place '/places/*id', :controller => 'places', :action => 'show'
map.connect '/places/*id.:format', :controller => 'places', :action => 'show'

map.place map.connect, Rails , , place_url, place_path .. helpers .

, , place_controller.rb, ID , - XML:

id, suffix = params[:id].join('/').split('.') 
params[:format] = suffix ? suffix : "xml"
0

Source: https://habr.com/ru/post/1724580/


All Articles