2016-09-01 23 views
0

routes.rb文件看起來像:routes.rb中的路由順序是否重要?

resources :contents, only: [:show] 
get 'contents/by_hardware', to: 'contents#show_by_hardware' 

在此設置下我無法訪問contents/by_hardware路線。

但是,如果我以不同的順序安裝我的routes.rb文件,everthing的作品。

get 'contents/by_hardware', to: 'contents#show_by_hardware'  
resources :contents, only: [:show] 

routes.rb文件中的順序是否重要?

+3

我很難相信在問這個問題時有906分的那個人沒有閱讀文檔 –

回答

5

是的,順序非常重要。

它的工作原理是這樣的:resources :contents, only: [:show]創建此航線

content GET /contents/:id(.:format)  contents#show 

所以,當你提出要求,例如,http://localhost:3000/contents/by_hardware,它是這條路線,這個URL匹配。它使用params {'id' => "by_hardware"}調用ContentsController#show行爲。您的自定義操作未被考慮,因爲匹配路線已經找到。

1

是的,這是很重要的,該航線將自上而下相匹配,使得您可以將上述資源路線get 'contents/by_hardware', to: 'contents#show_by_hardware'解決您的問題

1

肯定。路由器將匹配從頂部的第一條路線

2

是的,訂單確實很重要。而不是定義在兩個不同的地方在同一控制器的路線,我會建議你定義對於上述方案的路線這樣

resources :contents, only: [:show] do 
    get :show_by_hardware, on: :collection, path: :by_hardware 
end 

希望幫助!