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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35983628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:23:33  来源:igfitidea点击:

Undefined instance method "respond_to" in Rails 5 API Controller

ruby-on-railsrubyrestruby-on-rails-5

提问by アレックス

In rails 5 created with --apiI have an error

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

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

However, in the documentation for rails 4.2 it says http://edgeguides.rubyonrails.org/4_2_release_notes.html

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

respond_with and the corresponding class-level respond_to have been moved to the responders gem. Add gem 'responders', '~> 2.0' to your Gemfile to use it:

Instance-level respond_to is unaffected:

response_with 和相应的类级别 respond_to 已移至响应者 gem。将 gem 'responders', '~> 2.0' 添加到您的 Gemfile 中以使用它:

实例级 respond_to 不受影响:

And I'm calling the instance method. What's the matter?

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

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

回答by max

ActionController::APIdoes not include the ActionController::MimeRespondsmodule. If you want to use respond_toyou need to include MimeResponds.

ActionController::API不包括ActionController::MimeResponds模块。如果要使用respond_to,则需要包含MimeResponds.

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


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

Source: ActionController::API docs

来源:ActionController::API 文档

回答by jpalmieri

As of Rails 4.2, this functionality no longer ships with Rails, but can easily be included with the responders gem (like Max noted in comments above).

从 Rails 4.2 开始,这个功能不再随 Rails 一起提供,但可以很容易地包含在响应者 gem 中(就像上面评论中提到的 Max)。

Add gem 'responders'to your Gemfile, then

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

$ bundle install
$ rails g responders:install

Sources:
http://edgeguides.rubyonrails.org/4_2_release_notes.html#respond-with-class-level-respond-tohttps://github.com/plataformatec/responders

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