Gem jsonapi-serializerの基本的な使い方まとめ
jsonapi-serializerの基本的な使い方をまとめました!!
以前はfast_jsonapiと呼ばれていたようです!
現在もアップデートされ続けており、アップデートするたびに他のシリアライザーより処理時間が速くなっているのを保証すると Github に書いてあります!
すごい!
Gemfileに追加
gem 'jsonapi-serializer'インストール
$ bundle installモデルクラスを指定してシリアライザークラスを作成します。
$ rails g serializer Article
Running via Spring preloader in process 40421
create app/serializers/article_serializer.rbシリアライザークラスは以下のように書きます。
set_idには欲しいidを、attributesには欲しいカラムを書きます。
set_id :user_idという書き方も可能です!
class ArticleSerializer
include JSONAPI::Serializer
set_type :article
set_id :id
# 欲しいカラム
attributes :title, :contents, :status
# 欲しい関連付け
belongs_to :user
endAPI を以下のように作成します。
class Api::V1::ArticlesController < ApplicationController
def index
articles = Article.all
json_string = ArticleSerializer.new(articles).serialized_json
render json: json_string
endこの API にリクエストを送ると以下のようなレスポンスが返ってきます。
"data": [
{
"id": "1",
"type": "article",
"attributes": {
"title": "MyString1",
"contents": "MyText1",
"status": "draft"
},
"relationships": {
"user": {
"data": {
"id": "1",
"type": "user"
}
}
}
},
{
"id": "2",
"type": "article",
"attributes": {
"title": "MyString2",
"contents": "MyText2",
"status": "draft"
},
"relationships": {
"user": {
"data": {
"id": "2",
"type": "user"
}
}
}
},
.
.
.belongs_to :userによって関連付けしたuserのid,typeが帰ってきています。
"relationships": {
"user": {
"data": {
"id": "1",
"type": "user"
}
}
}これはhas_manyの場合も同様です。
以下の方法で関連付け先の詳細な値を取得できます。
class ArticleSerializer
include FastJsonapi::ObjectSerializer
set_type :article
set_id :id
attributes :title, :contents, :status
attribute :article_user do |object|
"#{object.user.name}"
end
end以下の記述で新たに返却するカラムを作成し、その中で関連付け先のuserの名前を指定しています。
attribute :article_user do |object|
"#{object.user.name}"
end以下のレスポンスを取得
"data": {
"id": "1",
"type": "article",
"attributes": {
"title": "MyString1",
"contents": "MyText1",
"status": "draft",
"article_user": "MyString1"
}リクエストで受け取ったパラメーターから返却する値を変えることもできます。
attribute :can_view_early do |movie, params|
params[:current_user].is_employee? ? true : false
end以下のようにオブジェクトごとにリンクを作成することもできます。
class ArticleSerializer
include FastJsonapi::ObjectSerializer
set_type :article
set_id :id
attributes :title, :contents, :status
belongs_to :user
link :custom_url do |object|
"http://article.com/#{object.title}"
end
link :personalized_url do |object, params|
"http://article.com/#{object.title}-#{object.user.email}"
end
end以下のようなレスポンスが返ります。
{
"id": "1",
"type": "article",
"attributes": {
"title": "MyString1",
"contents": "MyText1",
"status": "draft"
},
"relationships": {
"user": {
"data": {
"id": "23",
"type": "user"
}
}
},
"links": {
"custom_url": "http://article.com/MyString1",
"personalized_url": "http://articles.com/MyString1-user1@example.com"
}
}まとめは以上になります!
何か連絡をしたい際は以下 SNS、メールでお願いいたします。
Twitter: https://twitter.com/naka_ryo_z
見出しへのリンク