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はこちら