Rails 5 API 控制器中未定义的实例方法“respond_to”

问题描述 投票:0回答:2

在使用

--api
创建的 Rails 5 中,我有一个错误

NoMethodError (undefined method `respond_to' for #<Api::MyController:0x005645c81f0798>
Did you mean?  respond_to?):

但是,在 Rails 4.2 的文档中,它说 http://edgeguides.rubyonrails.org/4_2_release_notes.html

respond_with 和对应的类级别的respond_to 已经 移至响应者宝石。将 gem 'responders', '~> 2.0' 添加到您的 Gemfile 使用它:

实例级respond_to不受影响:

我正在调用实例方法。怎么了?

class ApplicationController < ActionController::API
end

# ...
class Api::MyController < ApplicationController

  def method1
    # ...
    respond_to do |format|
      format.xml { render(xml: "fdsfds") }
      format.json { render(json: "fdsfdsfd" ) }
    end
ruby-on-rails ruby rest ruby-on-rails-5
2个回答
138
投票

ActionController::API
不包括
ActionController::MimeResponds
模块。

class ApplicationController < ActionController::API
  include ActionController::MimeResponds
end


module Api
  class MyController < ApplicationController
    def method1
      # ...
      respond_to do |format|
        format.xml { render(xml: "fdsfds") }
        format.json { render(json: "fdsfdsfd" ) }
      end
    end
  end
end

来源:ActionController::API 文档


19
投票

从 Rails 4.2 开始,此功能不再随 Rails 一起提供,但可以轻松包含在响应者 gem 中(如上面评论中提到的 Max)。

gem 'responders'
添加到您的 Gemfile,然后

$ bundle install
$ rails g responders:install

来源:
http://edgeguides.rubyonrails.org/4_2_release_notes.html#respond-with-class-level-respond-to https://github.com/plataformatec/responders

© www.soinside.com 2019 - 2024. All rights reserved.