使用可选参数进行路由 [英] Routing with an optional parameter

查看:85
本文介绍了使用可选参数进行路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在路由文件中添加了

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 ?

谢谢!

PS。
我知道我可以将year用作?year = XXXX的参数,但我想将year用作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及以上。颠倒这两个路线的定义可以解决此问题(请参见下面的Alessandro评论)。

The above answer is only for rails 3 and above. Inverting the two routes definitions fixed the problem (see Alessandro's comment below).

这篇关于使用可选参数进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆