Jay
Jay

Reputation: 5084

Ruby on Rails - Nested Route Collections

I want to setup a GET endpoint in the format of:

api/v1/users/types/{type_id}

Example: > api/v1/users/types/10

My current routing looks like this:

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

This is incorrect and it throws an error: ArgumentError: can't use collection outside resource(s) scope. What's the correct formatting of routes for my requirement?

Upvotes: 0

Views: 252

Answers (2)

Chivorn Kouch
Chivorn Kouch

Reputation: 349

I believe the answer is:

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 is the action and what you need is the params :type_id. if you run rails routes, you get:

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

Now you can go to http://localhost:3000/api/v1/users/types/10

Upvotes: 2

Norly Canarias
Norly Canarias

Reputation: 1736

Try this

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                                                   

Here I used resource instead of resources for user. And moved the types into resources.

Upvotes: 2

Related Questions