Ruby on Rails: Routing for a tree hierarchy of pla

2020-06-25 04:23发布

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"?

2条回答
爷的心禁止访问
2楼-- · 2020-06-25 04:57

I tweaked Cody's answer above slightly to come up with this:

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

By using map.place instead of map.connect, Rails knows what resource we're dealing with and generated place_url, place_path etc helpers correctly.

Now, the 2nd line should work but doesn't thanks to the bug above, so here's a workaround for places_controller.rb that manually splits the ID and sets the format, defaulting to XML:

id, suffix = params[:id].join('/').split('.') 
params[:format] = suffix ? suffix : "xml"
查看更多
霸刀☆藐视天下
3楼-- · 2020-06-25 05:05

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.

查看更多
登录 后发表回答