了解rails中的'GET'路由

时间:2017-10-17 13:31:26

标签: ruby ruby-on-rails-4

在我的路线文件中,我指定了:

resources :cards do
end

除了基本的CRUD路线外,我还有另一条路线如下:

get '/cards/get_schema' => 'cards#get_schema'

当我点击此端点时,我实际上被带到了cards#show。为什么会这样?

3 个答案:

答案 0 :(得分:1)

resources :cards生成的一条路线为get '/cards/:id'。你能看到这个问题吗? get_schema被识别为id。试试这个

resources :cards do
  get 'get_schema', on: :collection
end

或者只是把那条路线放在最上面

get '/cards/get_schema' => 'cards#get_schema'
resources :cards

答案 1 :(得分:1)

  

这取决于定义的路线的顺序。

订单1

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :cards do
  end

  get '/cards/get_schema' => 'cards#get_schema'
end

运行路线

rake routes

<强>输出

~/D/p/p/s/console_test> rake routes
          Prefix Verb   URI Pattern                 Controller#Action
           cards GET    /cards(.:format)            cards#index
                 POST   /cards(.:format)            cards#create
        new_card GET    /cards/new(.:format)        cards#new
       edit_card GET    /cards/:id/edit(.:format)   cards#edit
            card GET    /cards/:id(.:format)        cards#show #<======== 
                 PATCH  /cards/:id(.:format)        cards#update
                 PUT    /cards/:id(.:format)        cards#update
                 DELETE /cards/:id(.:format)        cards#destroy
cards_get_schema GET    /cards/get_schema(.:format) cards#get_schema #<========

由于show预计cards/:id且高于/cards/get_schema,因此会将其路由到cards#show

订单2

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  get '/cards/get_schema' => 'cards#get_schema'

  resources :cards do
  end

end

运行路线

rake routes

<强>输出

  ~/D/p/p/s/console_test> rake routes
          Prefix Verb   URI Pattern                 Controller#Action
cards_get_schema GET    /cards/get_schema(.:format) cards#get_schema #<========
           cards GET    /cards(.:format)            cards#index
                 POST   /cards(.:format)            cards#create
        new_card GET    /cards/new(.:format)        cards#new
       edit_card GET    /cards/:id/edit(.:format)   cards#edit
            card GET    /cards/:id(.:format)        cards#show #<========
                 PATCH  /cards/:id(.:format)        cards#update
                 PUT    /cards/:id(.:format)        cards#update
                 DELETE /cards/:id(.:format)        cards#destroy

在此方案中,/cards/get_schema将为顶级,不会与cards#show

冲突

答案 2 :(得分:1)

Rails将get_schema视为卡片的ID。解决方案是重新排序路由声明,如下所示:

get '/cards/get_schema' => 'cards#get_schema'

resources :cards do
end

这样get_schema路线将在show路线之前匹配。