xiaoqiu369

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  7 Posts :: 3 Stories :: 2 Comments :: 0 Trackbacks

Rails Routing from the Outside In
http://guides.rails.info/routing_outside_in.html
这篇文章将介绍Rails routing针对用户方面的一些特性.参考这篇文章,你将会学到以下知识:
a.理解routing的作用
b.破解routes.rb内的代码
c.构建你自己的routes,可以用classic hash样式或现在流行的RESTful样式.
d.识别route怎样与controller和action映射.

1.The Dual Purpose of Routing

Rails routing 有两种机制,你可以将trees转换为pager,或把paper转换回trees.具体地说,它可以连接收到的请求与你应用程序的控制器的代码和帮你生成URLs,而不用做为一个字符串硬编码.

1.1connecting URLs to Code;
当你的应用程序收到的请求为:
GET /patients/17
Rails里的路由引擎就是一段分发这个请求到应用程序合适的位置进行处理的一段代码.在这个案例中,这个应用程序很可能以运行patients控制器里的show结束.显示patients ID为17的详细信息.

1.2 Generateing URLs from Code
Routing 也可以反过来运行,如果你的应用程序中包含这样的代码:

@patient=Patient.find(17)
<%= link_to "Patient Record",patient_path(@patient)%>

这时路由引擎转换这个链接到一个URL:http://example.com/patients/17.以这种方式你可以降低应用程序的脆弱性,使你的代码更加容易阅读和理解.

Patient 必须作为一个resource被声明为一个资源,通过named route来转换.

2.Quick Tour of Routes.rb

在Rails中routing有两种组件,routing engine本身,它做为Rails的一部分,config/routes.rb文件,它包含实际的可用在应用程序中的routes.

2.1 Processing the File
在形式上,Routes.rb文件也就是一个大大的block,会被放入ActionController::Routing::Routes.draw.
在这个文件中有五种主要的样式:
RESTful Routes
Named Routes
Nested Routes
Regular Routes
Default Routes

2.2 RESTful Routes
RESTful Routes 利用rails嵌入式REST方法来将routing的所有信息包装为一个单独的声明.eg: map.resource :books

2.3 named Routes
named routes 在你的代码中给你很可读的链接,也可以处理收到的请求

map.login '/login' ,:controller=>'session',:action=>'new'

2.4 Nested routes

Nested routes可以在一个资源里声明另一个资源.

map.resources :assemblies do |assemblies|
 assemblies.resources :parts
end

2.5 Regular Routes
map.connect 'parts/:number',:controller=>'inventory',:action=>'show'

2.6 Default Routes
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'

posted on 2008-12-19 14:12 bobqiu 阅读(209) 评论(0)  编辑  收藏 所属分类: ruby&rails

只有注册用户登录后才能发表评论。


网站导航: