【问题标题】:Undefined instance method "respond_to" in Rails 5 API ControllerRails 5 API 控制器中未定义的实例方法“respond_to”
【发布时间】:2016-06-29 06:15:11
【问题描述】:

在使用--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

【问题讨论】:

  • “怎么了?” – 嗯,发行说明是针对 4.2 的,而您使用的是 5?
  • @JörgWMittag,自 4.2 以来一直没有提及更改 meme-responds,因此它仍然非常相关。
  • 您可能想尝试响应者 gem。真是太棒了。
  • @max,有什么宝石不好看吗?它让你屏住呼吸,让你大喊“哇哇哇哇,太棒了,哇哇哇哇!!!”还是什么?
  • 有很多只是 meh 的宝石。 Responders 真的可以让你跳过一堆样板文件并干掉你的控制器。我特别推荐它用于 API。

标签: ruby-on-rails ruby rest ruby-on-rails-5


【解决方案1】:

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

来源:ActionController::API docs

【讨论】:

    【解决方案2】:

    从 Rails 4.2 开始,此功能不再随 Rails 提供,但可以轻松包含在响应者 gem 中(就像上面 cmets 中提到的 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

    【讨论】:

    • 引用链接源“实例级响应不受影响”。如果像 OP 一样,您只使用实例级 respond_to 您不需要响应者 gem,只需确保 ActionController::MimeResponds 已包含在您的控制器中。
    猜你喜欢
    • 2016-11-30
    • 1970-01-01
    • 2023-04-08
    • 2011-06-16
    • 2017-05-25
    • 2016-12-19
    • 2012-07-18
    • 2017-11-08
    • 2019-09-13
    相关资源
    最近更新 更多