Ruby on Rails - Nested Route Collections

Dinuka Jay

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?

Chivorn Kouch

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related