2017-10-17 48 views
0

在我的路线文件我已经指定了:理解“GET”在轨线路

resources :cards do 
end 

除了基本的CRUD路线我已经另一条路线是如下:

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

当我打这个终点,我实际上被带到了cards#show。为什么会发生?

回答

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

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 #<======== 

由于节目预计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

1

Rails的冲突处理get_schema作为卡的ID。解决的办法是重新安排航线的声明,就像这样:

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

resources :cards do 
end 

这样的get_schema路线将show路线之前进行匹配。