Question

I have an api tokens controller based on Matteo Melanis blog post. I'd like to add two custom actions register and unregister to the controller, and so the route that looked like this

namespace :api do
  namespace :v1  do
    resources :tokens,:only => [:create, :destroy]
  end
end

has now become this

namespace :api do
  namespace :v1  do
    resources :tokens do
      put 'register', on: :member, as: :register
      delete 'unregister', on: :member, as: :unregister
    end
  end
end

This is the only way I've found that doesn't let unregister suppress the CRUD destroy action, associated with the DELETE verb. I tried to do

resources :tokens, :only => [:create, :destroy, :register, :unregister] do

in the above code, as well as defining resources :tokens,:only => [:create, :destroy] in parallel to the block. Yet, I either get the undesirable all CRUD + custom actions, or one of the custom actions overriding a CRUD action.

In short, I'd like to end up with

     register_api_v1_token PUT    /api/v1/tokens/:id/register(.:format)   api/v1/tokens#register
   unregister_api_v1_token DELETE /api/v1/tokens/:id/unregister(.:format) api/v1/tokens#unregister
             api_v1_tokens GET    /api/v1/tokens(.:format)                api/v1/tokens#index
                           POST   /api/v1/tokens(.:format)                api/v1/tokens#create
                           DELETE /api/v1/tokens/:id(.:format)            api/v1/tokens#destroy

Is this possible, and if yes: how can I make it so?

Was it helpful?

Solution

This should work:

resources :tokens, only: [:create, :destroy] do
  member do
    put 'register'
    delete 'unregister'
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top