带有可选参数的路由 [英] Routing with an optional parameter
本文介绍了带有可选参数的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在路由文件中添加:
map.show_book "/show_book/:name/year/:year", :controller => "book", :action => "show_version"
我还补充了:
map.show_book "/show_book/:name", :controller => "book", :action => "show_version"
显示最新的书而不指定年份.
to show the latest book without specifying the year.
但它不起作用,如果我不通过年份,它在show_book/NAME"中找不到路线.
But it doesn't work, it cannot find the route in "show_book/NAME" if I don't pass the year.
你知道为什么它不起作用吗?
Do you have some ideas why it doesn't work ?
谢谢!
附注.我知道我可以使用?year=XXXX"作为参数使用年份,但我想使用年份作为 URL 的一部分
PS. I know that I can use year as parameter with "?year=XXXX", but I want to use the year as a part of the URL
推荐答案
map.show_book "/show_book/:name(/year/:year)", :controller => "book", :action => "show_version"
并删除第二条路线.
更新
以上答案仅适用于 rails 3 及以上版本.反转两个路由定义解决了这个问题(见下面亚历山德罗的评论).
The above answer is only for rails 3 and above. Inverting the two routes definitions fixed the problem (see Alessandro's comment below).
这篇关于带有可选参数的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文