如何在 Rails 5 API 模式中包含 "new" 路由 [无法找到操作 'show']

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

目前我遇到了这个错误

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

我的路线文件看起来像这样

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

我还可以看到资源方法没有按照 the docs

创建新端点

我暂时这样做了,但我很想知道是否有更清晰的修复方法:

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

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

  def new
    ...

你想要表演路线吗?如果这样做,则需要添加 show 方法。您实际上不必在其中放置任何东西。

def show; end

如果您不想包含显示路线并仍然使用资源助手,您可以始终在您的资源中使用 onlyresources :images, only: [:new]

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

或者,如果您想对多个资源执行此操作,请使用路由问题:

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

我认为当您的应用程序在 运行 api 唯一模式。如果您想对所有路线执行此操作,则必须使用 monkeypatch ActionDispatch::Routing::Mapper::Resources 来更改行为。