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

时间:2016-03-14 09:23:50

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

在使用for index, value in enumerate(a):创建的rails 5中,我有一个错误

--api

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

  

respond_with和相应的类级别respond_to   转移到响应者宝石。添加gem'响应者','〜> 2.0'到你的   Gemfile使用它:

     

实例级的respond_to不受影响:

我正在调用实例方法。这是怎么回事?

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

2 个答案:

答案 0 :(得分:80)

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

答案 1 :(得分:12)

从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