【问题标题】:How to include the "new" routes in Rails 5 API mode [The action 'show' could not be found]如何在 Rails 5 API 模式中包含“新”路由 [找不到动作“显示”]
【发布时间】:2020-05-18 01:38:02
【问题描述】:

目前我收到此错误

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
    ...

【问题讨论】:

    标签: ruby-on-rails routes actioncontroller


    【解决方案1】:
    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 模式下运行时,我认为实际上没有选项可以将 newedit 路由重新添加到 resources 调用中。如果您想为所有路线执行此操作,则必须使用 monkeypatch ActionDispatch::Routing::Mapper::Resources 更改行为。

    【讨论】:

      【解决方案2】:

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

      def show; end

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-23
        • 1970-01-01
        • 1970-01-01
        • 2015-05-23
        相关资源
        最近更新 更多