Home > Net >  Named route without the namespace prefix
Named route without the namespace prefix

Time:04-28

We have defined a route to a resource_owner_info controller as follows:

  namespace :api, default: { format: :json } do
    namespace :v1 do
      get '/me', to: 'resource_owner_info#me', as: 'resource_owner_info'
      # other /api/v1 routes follow
      ...
    end
  end

This generates the named route api_v1_resource_owner_info. I'd prefer to remove the api_v1_ prefix from these routes, but still have the endpoint be /api/v1/... etc. Can that be done in Rails?

CodePudding user response:

Pretty sure you have to do this outside of the namespace:

get 'api/v1/me', to: 'api/v1/resource_owner_info#me', as: 'resource_owner_info', defaults: { format: :json }

If you have a lot of routes like that:

scope path: :api, module: :api, defaults: { format: :json } do
  scope path: :v1, module: :v1 do
    get 'me', to: 'resource_owner_info#me', as: 'resource_owner_info'
    # ...
  end
end

Both will generate this

Prefix              Verb  URI Pattern            Controller#Action
resource_owner_info GET   /api/v1/me(.:format)   api/v1/resource_owner_info#me {:format=>:json}

https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html

  • Related