ruby-on-railsroutesactioncontroller

How to include the "new" routes in Rails 5 API mode [The action 'show' could not be found]


currently I'm getting this error

The action 'show' could not be found for Api::V1::ImagesController

my routes file looks like this

namespace :api do
    namespace :v1 do
        ...
        resources :images
        ...
    end
end

I can also see that the resources method has not created the new endpoint as per the docs

Ive done this for the time being, but I would love to know if there is a cleaner fix:

class Api::V1::ImagesController < Api::BaseController

  def show
    new if params[:id] == "new"
  end

  def new
    ...

Solution

  • namespace :api do
      namespace :v1 do
        resources :images do
          get :new
        end
      end
    end
    

    Or if you want to do this to multiple resources use a routing concern:

    concern :has_new do
      get :new
    end
    
    namespace :api do
      namespace :v1 do
        resources :images, concerns: :has_new
        resources :videos, concerns: :has_new
      end
    end
    

    I don't think there is actually an option to re-add the new and edit routes to the resources call when your application is running in api only mode. And you would have to monkeypatch ActionDispatch::Routing::Mapper::Resources to change the behavior if you wanted to do this for all your routes.