1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ruby on Rails コントローラーで JSON および CSV フォーマットに対応する方法

Posted at

皆さん、こんにちは。

今回は「Ruby on Rails コントローラーで JSON および CSV フォーマットに対応する方法」について紹介させていただきます。

#Ruby on RailsコントローラーでJSONおよびCSVフォーマットに対応する方法

Ruby on Rails のコントローラーでは、respond_to を使って複数のレスポンスフォーマット(JSON や CSV など)に対応することが可能です。

🧩 実装例

以下は、ユーザー一覧を JSON と CSV の両形式で返すサンプル実装です。

class UsersController < ApplicationController
  require 'csv'

  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
      format.csv do
        send_data generate_csv(@users),
                  filename: "users-#{Date.today}.csv",
                  type: 'text/csv'
      end
    end
  end

  private

  def generate_csv(users)
    CSV.generate(headers: true) do |csv|
      csv << ["ID", "名前", "メールアドレス", "作成日"]

      users.each do |user|
        csv << [user.id, user.name, user.email, user.created_at]
      end
    end
  end
end

対応するエンドポイント例

  • エンドポイントの使用例

    • JSON 形式で取得: /users.json
    • CSV 形式で取得: /users.csv
  • 補足
    routes.rbでリソースルーティングを定義しておくことで、上記のエンドポイントが利用可能になります。

resources :users, only: [:index]

まとめ

Rails のrespond_toを使えば、簡単にJSONCSVに対応できます。
API やデータエクスポート機能の一部として、ぜひ取り入れてみてください!

今日は以上です。

ありがとうございました。
よろしくお願いいたします。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?