2016-09-01 22 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 

希望帮助!