有名路由

到现在我们已经在routes.rb 文件中使用map.connect 创建了匿名的“路由器”。通常
这就足够了;Rails 会做好由我们传递给url_for()等的给定参数创建的URL 的挑选工作。当
然,我们可以给出“路由器”的名字,以让我们应用程序更容易理解。这不会修改引入URL
的解析,但它会让我们在代码中能明确指定生成URL 的“路由器”。
你在“路由器”定义内使用一个名字而不是connect 来简单地创建一个有名字的“路由
器”。你使用的名字会变成那个特定“路由器”的名字。例如,我们可以像下面那样重新编
码我们的博客的“路由器”。
ActionController::Routing::Routes.draw do |map|
# Straight 'http://my.app/blog/' displays the index
map.index "blog/",
:controller => "blog",
:action => "index"
# Return articles for a year, year/month, or year/month/day
map.date "blog/:year/:month/:day",
:controller => "blog",
:action => "show_date",
:requirements => { :year => /(19|20)dd/,
:month => /[01]?d/,
:day => /[0-3]?d/},
:day => nil,
:month => nil
# Show an article identified by an id
map.show "blog/show/:id",
:controller => "blog",
:action => "show",
:id => /d+/
# Regular Rails routing for admin stuff
map.admin "blog/:controller/:action/:id"
# Catch-all so we can gracefully handle badly-formed requests
map.catchall "*anything",
:controller => "blog",
:action => "unknown_request"
end
这儿,我们用显示索引的index 作为“路由器”的名字,接受日期的“路由器”名字是
date,等等。我们现在可以使用这些名字来生成URL,这是通过附加_url 给它们的名字并按
我们先前使用url_for()的同样方式使用它们。因此,用于生成博客的index 的URL,我们可
以使用
@link = index_url
这将使用第一个“路由器”来构造URL,结果像下面这样:
http://pragprog.com/blog/
你可以传递额外的参数,它被视为这些有名字“路由器”组成的哈希表。参数将被缺省
地添加给特定的“路由器”。下面例子显示了这点。
index_url
#=> http://pragprog.com/blog
date_url(:year => 2005)
#=> http://pragprog.com/blog/2005
date_url(:year => 2003, :month => 2)
#=> http://pragprog.com/blog/2003/2
show_url(:id => 123)
#=> http://pragprog.com/blog/show/123
你可以在Rails 期望URL 做为参数的任何地方使用一个xxx_url 方法。因此你可以使用
下面代码来重定向到index 页面。
redirect_to(index_url)
在view 模板中,你可以使用index 来创建一个超链接。
<%= link_to("Index", index_url) %>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值