Ruby on Rails,Routes配置routes.rb及請求解析規則
在中我們知道,頁面提交給web伺服器的請求先是嘗試直接查詢並返回public目錄中的資源,如果沒有找到則將請求交給Rails的Routes。Routes根據路由配置,將請求轉化為對Controller中的Action並呼叫之。Routes的配置可說的細節很多,最開始我們先關注三種最簡單的方式:Simple route,Default route,Root route。Routes的配置資訊存放在config/routes.rb檔案當中。
當前我的routes.rb檔案如下所示,大段被註釋掉的內容是各種配置用法的舉例先不用理會,其中第二行get "demo/index"這句就是在《Ruby
on Rails,建立最簡單的檢視/控制器單元Hello World
在Routes配置檔案中,越靠上的一行配置擁有越高的優先順序。
get "demo/index"的意思是將demo/index的請求呼叫名為demo的Controller中名為index的Action。SimpleSite::Application.routes.draw do get "demo/index" # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => 'welcome#index' # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id))(.:format)' end
match "demo/index", :to => "demo#index"
這種路由配置最簡單易懂但是比較不易於維護,因為我們要在每次增加檢視/控制器時維護Routes配置。我們想使用一個更加通用的規則,在這個規則的幫助下我們修改檢視/控制器規則後依然能夠工作-Default route。
get /:controller/:action/:id的意思是呼叫名為demo的Controller中名為index的Action並傳入id值。
routes.rb檔案的最下面也就是優先順序最低的一條配置既是Default route規則。如果傳入的請求沒有能夠匹配Routes配置中的任何一條規則,則將按照這一條規則對請求進行解析。我們將這條規則前的註釋符號刪除,以便啟用這條規則,同時也就不需要檔案頂部的那條get "demo/index"。match ':controller(/:action(/:id(.:format)))'
SimpleSite::Application.routes.draw do
match ':controller(/:action(/:id))(.:format)'
end
修改了routes.rb之後需要重啟伺服器。請求“localhost:3000/demo/index”依然能夠轉向之前的頁面,說明Default route配置包含了之前Simple route的情況。
由於我們之前刪除了public目錄中的index.html,所以當以“localhost:3000/”請求時將沒有規則能夠匹配“/”。
這時,我們需要配置Root route。
root :to => "demo#index"
此時route.rb如下SimpleSite::Application.routes.draw do
root :to => "demo#index"
match ':controller(/:action(/:id))(.:format)'
end