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