6
0

More than 3 years have passed since last update.

【Ruby on Rails】gem "jsonapi-serializer"の基本的な使い方

Last updated at Posted at 2021-02-02

RailsAPIモードで開発をする際に、JSONを整形するためにjsonapi-serializerというものを使用している。
このgemに関してgoogle検索してもほとんど日本語の記事が出てこないため、基本のことではあるがここにメモしておく。

users_controller.rb
module Api::V1::Admin
  class CompaniesController < ApplicationController

    def index
      companies = User.all
      json_string = CompanySerializer.new(users)
      render json: json_string
    end
  end
end

コントローラを作成したら、serializers/user_serializer.rbを作成する。

user_serializer.rb
class CompanySerializer
  include JSONAPI::Serializer

  has_many :likes
  attribute :name, :email, :address
end

このように記述すると思いどおりのJSONを受け取ることができる。

ちなみに、user_serializer.rbにあるinclude JSONAPI::Serializerこれは記述しなくてもシリアライザーとして機能するみたい。

jsonapi-serializerのGitHubはこちら

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