Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

ruby - Undefined instance method "respond_to" in Rails 5 API Controller

In rails 5 created with --api I have an error

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

However, in the documentation for rails 4.2 it says 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:

And I'm calling the instance method. What's the matter?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ActionController::API does not include the ActionController::MimeResponds module. If you want to use respond_to you need to include 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

Source: ActionController::API docs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...