Mat
Mat

Reputation: 1011

Rails : add namespace to resource

I currently have this in my routes.rb :

namespace :api
  namespace :v1
   namespace :me
    # ...
    resources :offers do
     resources :state, only: %i(index)
    end
  end
 end
end

This gives me this route :

GET v1/me/offers/:offer_id/state(.:format)
api/v1/me/state#index

But the route I would like to have is this one :

GET v1/me/offers/:offer_id/state(.:format)
api/v1/me/offers/state#index

Simply put, I want to be able to place my state_controller.rb in an offers folder, without changing the path to access it. How can I achieve that ?

Upvotes: 5

Views: 2984

Answers (3)

Mat
Mat

Reputation: 1011

I found a better way to do it : use module

resources :offers, module: :offers do
  resources :state, only: %i(index)
end

Upvotes: 10

Richard Peck
Richard Peck

Reputation: 76774

namespace :api
  namespace :v1
   namespace :me
    # ...
    resources :offers do
      namespace :offers, path: "" do
        resources :state, only: %i(index)
      end
    end
  end
 end
end

Upvotes: 2

dimakura
dimakura

Reputation: 7655

You should define controller for your resources explicitly:

resources :state, controller: 'offers/state'

This will route requests to app/controllers/api/v1/me/offers/state_controller.rb.

Upvotes: 2

Related Questions