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

实例级响应不受影响:

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

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

推荐答案

ActionController::API不包括ActionController::MimeResponds模块.如果你想使用respond_to,你需要包括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 docs

Ruby-on-rails相关问答推荐

如何将POST-CSSS-IMPORT与TRANWIND-RACKS和IMPORT映射一起使用

select2 未应用于所有下拉列表;它只适用于数据的最后一条记录

为 ActionMailer 渲染不同的视图(模板)

Rails 模型方法 self.与普通

FactoryGirl + Faker - 为数据库种子数据中的每个对象生成相同的数据

Rails 模型:您将如何创建一组预定义的属性?

水豚 click_link 与 :href 匹配

Rails 5.1:未知 firstpos:NilClass - 问题重新加载应用程序

在本地 Rails 开发环境中获取真实 IP 地址

我应该将全局共享部分模板放在哪个文件夹中?

Django 还是 Ruby-On-Rails?

Rails 范围为 IS NOT NULL 并且不为空/空白?

在rails中带有内部文本或html的link_to image_tag

Rails Associations - has_many => :through - 但相同的模型

在 Rails 路由中更改 id 参数

何时使用 Helpers 而不是 Partials

获取完整的 rails 控制器名称,包括命名空间

资源和资源方法之间的区别

Ruby on Rails:Cucumber:我如何获取单个功能?

如何测试也定义为辅助方法的 ApplicationController 方法?