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'