Rails 5 API 控制器中未定义的实例方法 "respond_to"
Undefined instance method "respond_to" in Rails 5 API Controller
在 rails 5 创建 --api
我有一个错误
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:
Instance-level respond_to is unaffected:
我正在调用实例方法。怎么了?
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
从 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
在 rails 5 创建 --api
我有一个错误
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:
Instance-level respond_to is unaffected:
我正在调用实例方法。怎么了?
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
从 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