0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】 APIモードでJSONレスポンスを加工・整形する方法(as_json / only / include)

0
Posted at

はじめに

本記事では、RailsのAPIモードで、フロントエンドで表示したいデータに合わせて JSON データを整形・加工する方法についてまとめます。

特に、モデルのデータをそのまま返すのではなく、必要なカラムに絞り込む as_json の使い方をメインとして備忘録を残します。

as_json を使うことで、フロントエンドで必要なデータだけに絞ったレスポンスを返せるようになります。

前提

  • Ruby on Rails の基本的な操作(CRUDなど)を理解している方
  • Rails APIモードをこれから触りたい方

Rails API 環境構築

環境構築

新規プロジェクトをAPIモードで作成するコマンドです。

# 基本的なAPIモードの作成
rails new my_api --api

# DBにPostgreSQLを指定し、テストフレームワークを除外
rails new my_api --api -T -d postgresql

準備

# ActiveRecord::NoDatabaseErrorが出るのでデータベースを作成する
rails db:create

# サーバー起動
rails s

User作成

rails g model User name:string hobby:string
rails db:migrate
rails g controller Users
users_controller.rb
class UsersController < ApplicationController
  def index
    @users = User.all
    render json: @users
  end
end
user.rb
class User < ApplicationRecord
  has_many :articles
end

Article作成

rails g model Article content:text user:references
rails db:migrate
rails g controller Articles
articles_controller.rb
class ArticlesController < ApplicationController
  def index
    @articles = Article.all
    render json: @articles
  end
end
article.rb
class Article < ApplicationRecord
  belongs_to :user
end

データ投入

seeds.rb
user = User.create!(name: "taro", hobby: "プログラミング")
Article.create!(content: "テスト記事テスト記事", user: user)
Article.create!(content: "テスト記事です。テスト記事です", user: user)

データ作成コマンド実行

rails db:seed

ルーティング

routes.rb
Rails.application.routes.draw do
  resources :users, only: [ :index ]
  resources :articles, only: [ :index ]
end

user JSON

user
[
  {
    "id": 1,
    "name": "taro",
    "hobby": "プログラミング",
    "created_at": "2026-05-10T12:16:27.667Z",
    "updated_at": "2026-05-10T12:16:27.667Z"
  }
]

Image from Gyazo

article JSON

article
[
  {
    "id": 1,
    "content": "テスト記事テスト記事",
    "user_id": 1,
    "created_at": "2026-05-10T12:16:27.673Z",
    "updated_at": "2026-05-10T12:16:27.673Z"
  },
  {
    "id": 2,
    "content": "テスト記事です。テスト記事です",
    "user_id": 1,
    "created_at": "2026-05-10T12:16:27.676Z",
    "updated_at": "2026-05-10T12:16:27.676Z"
  }
]

Image from Gyazo

JSONデータ加工

コントローラーで必要なデータをレンダリングする際、as_jsonを使用することで、必要なデータのカラムを抽出したり、関連付けたモデルからデータを取得できます。

onlyinclude を使って必要なカラムを抽出し、includes を使って関連データも効率よく取得します。

特定のカラムのみを抽出(only)

users_controller.rb
class UsersController < ApplicationController
  def index
    @users = User.all
    render json: @users.as_json(only: [ :id, :name ])
  end
end
user
[
  {
    "id": 1,
    "name": "taro"
  }
]

Image from Gyazo

関連テーブルのデータを含める (include)

users_controller.rb
class UsersController < ApplicationController
  def index
    @users = User.includes(:articles)

    render json: @users.as_json(
      only: [ :id, :name ],
      include: {
        articles: {
          only: [ :id, :content ]
        }
      }
    )
  end
end
user
[
  {
    "id": 1,
    "name": "taro",
    "articles": [
      {
        "id": 1,
        "content": "テスト記事テスト記事"
      },
      {
        "id": 2,
        "content": "テスト記事です。テスト記事です"
      }
    ]
  }
]

Image from Gyazo

おわりに

フロントで必要なデータに合わせて、JSON データを作ることは重要なことだと考えており、Rails でうまく JSON データ構造を作ることができれば、フロントでベストなデータ表示ができると思いました。

何より API として返却されたデータを、フロント側で設計通りに表示できたときは面白さを感じます。

本記事が参考になると幸いです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?