2017-11-04 180 views
0

我想設置的格式爲一個GET端點:Ruby on Rails的 - 嵌套路線集合

api/v1/users/types/{type_id}

例子:> api/v1/users/types/10

我當前的路由看起來是這樣的:

Rails.application.routes.draw do 
    namespace :api do 
    namespace :v1 do 
     resources :users do 
     collection do 
      # other routes in the same namespace 
      get "sync" 
      post "register" 

      # my attempt at making another collection for `types` 
      collection do 
      get "types" 
      end 

     end 
     end 
    end 
    end 
end 

這是不正確的,它會引發一個錯誤:ArgumentError: can't use collection outside resource(s) scope。根據我的要求,正確的路線格式是什麼?

+0

什麼控制器方法應該處理的要求嗎?你關心這個參數是叫'type_id'還是隻叫'id'。 – spickermann

+0

@spickermann沒有真正關注這個參數名稱 – Dinuka

回答

2

我相信答案是:

Rails.application.routes.draw do 
    namespace :api do 
    namespace :v1 do 
     resources :users do 
     collection do 
      get "sync" 
      post "register" 
      get "types/:type_id", action: 'types' 
     end 
     end 
    end 
    end 
end 

types是動作,你需要什麼PARAMS :type_id。 如果您運行rails routes,您可以:

 Prefix Verb URI Pattern       Controller#Action 
      GET /api/v1/users/types/:type_id(.:format) api/v1/users#types 

現在你可以去http://localhost:3000/api/v1/users/types/10

+0

這工作。謝謝! – Dinuka

2

試試這個

Rails.application.routes.draw do                             
    namespace :api do         
    namespace :v1 do         
     resource :users do        
     resources :types, only: :show, param: :type_id 
     collection do        
      # other routes in the same namespace   
      get "sync"         
      post "register"        
     end           
     end            
    end            
    end             
end             

在這裏,我對用戶使用的資源,而不是資源。並將這些類型轉化爲資源。

+0

這產生了這個>'/ api/v1/users /:type_id/users /:type_id/types(。:format)' – Dinuka

+0

對不起,爲什麼? – Dinuka