Ruby on Rails: Routing for a tree hierarchy of places

纵然是瞬间 提交于 2019-12-05 06:20:56

问题


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


回答1:


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.




回答2:


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"


来源:https://stackoverflow.com/questions/1837794/ruby-on-rails-routing-for-a-tree-hierarchy-of-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!