Undefined instance method "respond_to" in Rails 5 API Controller

Ruby on-RailsRubyRestRuby on-Rails-5

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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


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

Source: ActionController::API docs

Solution 2 - Ruby on-Rails

As of Rails 4.2, this functionality no longer ships with Rails, but can easily be included with the responders gem (like Max noted in comments above).

Add gem 'responders' to your Gemfile, then

$ bundle install
$ rails g responders:install

Sources:
http://edgeguides.rubyonrails.org/4_2_release_notes.html#respond-with-class-level-respond-to https://github.com/plataformatec/responders

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIncertezaView Question on Stackoverflow
Solution 1 - Ruby on-RailsmaxView Answer on Stackoverflow
Solution 2 - Ruby on-RailsjpalmieriView Answer on Stackoverflow