Arip Rahman
Arip Rahman

Reputation: 179

How to use namespace in rails without namespace in url

I have a question about routes in rails when using namespaces. Example code:

namespace :api do
    # /api/... Api::
    namespace :v1 do
      devise_for :users, :controllers => {sessions: 'api/v1/users/sessions', :registrations => "api/v1/users/registrations", :password => 'api/v1/users/passwords'}
      resources :events do
        namespace :informations do
          resources :agendas
          resources :attendees
          resources :polls
          resources :presentatios
          resources :speakers
          resources :sponsors
          resources :votes
          resources :vote_options
        end
      end
    end
  end

I check my url in console with grep agenda, and it results in:

/api/v1/events/:event_id/informations/agendas

How can I remove namespace information from url without removing namespace from routes?

Upvotes: 1

Views: 2207

Answers (1)

max
max

Reputation: 101811

You can use the module option to add a namespace (as in a module wrapping) to the controllers:

resources :events, module: 'v1/api'

    Prefix Verb   URI Pattern                Controller#Action
    events GET    /events(.:format)          v1/api/events#index
           POST   /events(.:format)          v1/api/events#create
 new_event GET    /events/new(.:format)      v1/api/events#new
edit_event GET    /events/:id/edit(.:format) v1/api/events#edit
     event GET    /events/:id(.:format)      v1/api/events#show
           PATCH  /events/:id(.:format)      v1/api/events#update
           PUT    /events/:id(.:format)      v1/api/events#update
           DELETE /events/:id(.:format)      v1/api/events#destroy

But it makes no sense to use a versioned API controller without versioned urls! That is unless you believe in either using a custom request header or custom accept type. Both of which had some diehard REST purist followers but are now scarce due to the the fact that they are just too dang difficult to test.

http://www.troyhunt.com/2014/02/your-api-versioning-is-wrong-which-is.html

Upvotes: 1

Related Questions