Ruby on Rails:位置树层次结构的路由
因此,我们有一个遗留系统,可以跟踪具有“Europe/France/Paris”等 ID 的地点,并且我正在构建一个 Rails 外观,将其转换为像 http://foobar/places/Europe/France/Paris 这样的 URL。这个要求是没有商量余地的,可能的关卡数量是无限的,而且我们也无法逃脱斜杠。
为 http://foobar/places/Europe 设置 paths.rb 很简单:
map.resources :places
...但是 http: // foobar/places/Europe/France 抱怨“没有对欧洲采取任何行动”。我尝试过:
map.connect '/places/:id', :controller => 'places', :action => 'show'
...但这给出了相同的结果,因为显然 :id 以第一个“/”结尾。如何使 ID 涵盖“地点”之后的所有内容?
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"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我稍微调整了科迪上面的答案,得出这样的结论:
通过使用map.place而不是map.connect,Rails知道我们正在处理什么资源并生成
place_url
,place_path
等助手正确。现在,第二行应该可以工作,但由于上面的错误而无法工作,因此这里有一个 place_controller.rb 的解决方法,它手动分割 ID 并设置格式,默认为 XML:
I tweaked Cody's answer above slightly to come up with this:
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:
查看路由指南以获取完整文档:
http://guides.rubyonrails.org/routing.html< /a>
特别是“4.9 路由通配”部分。
但我认为你真正想做的是声明你的路线,如下所示:
使用类似这样的 URL 调用
,你可以轻松地(重新)加入“/”以生成你想要的完整字符串“foo/bar/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:
Called with a URL like
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.