RailsのAPIモードでrespond_to を使うにはMimeRespondsをincludeする必要がある

こんにちは!kossyです!




さて、今回は、RailsAPIを作成する時にrespond_toを使いたい時はあるモジュールをincludeする必要があるという話をブログに残したいと思います。




環境
Rails 6.0.2.1(API only)
Ruby 2.5.1




ApplicationController.rbにMimeRespondsをincludeすればOK

CSVダウンロード機能を作成しようとした時に何気なく下記のようなコードを書いてみたら

def donwload
    csv_data = GoogleBookClient.instance.download(params[:books])

    respond_to do |format|
      format.all  { send_data csv_data }
    end
end

エラーに遭遇、、、

NoMethodError (undefined method `respond_to' for #<BooksController:0x00007f90d52739a0>
Did you mean?  respond_to?):


調べてみたところ、
ruby - Undefined instance method "respond_to" in Rails 5 API Controller - Stack Overflow

ActionController::API does not include the ActionController::MimeResponds module. If you want to use respond_to you need to include MimeResponds.

とのことで、どうやらActionController::MimeRespondsをincludeせにゃならんとのことでしたので、


app/controllers/application_controller.rb

class ApplicationController < ActionController::API
  include ActionController::MimeResponds
end

をincludeしたところ、

Sent data  (7.6ms)
Completed 200 OK in 42ms (Views: 7.3ms | ActiveRecord: 0.0ms | Allocations: 11840)

無事通信に成功しました。



参考にさせていただいたサイト

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