LoginSignup
2
2

More than 3 years have passed since last update.

active_model_serialiser 使い方

Last updated at Posted at 2019-08-08

active_model_serialiser とは?

(アクティブ・モデル・シリアライザー) は jbuilder の代わりに API を返すための gem 。

導入

gem ファイルに追記し bundle install をする。
このとき jbuilder 削除してよし。

Gemfile
gem 'active_model_serializers'
- gem 'jbuilder'

設定の数々

ディレクトリの作成

API 設計の観点からいくつかディレクトリの整理をすることがベスト。

app/controllers/api/v1/
/api/v1/ ディレクトリを自分で作成し上記の配置にする。

controller の配置

app/controllers/api/v1/〇〇_controller.rb
先ほど作成したディレクトリに controller ファイルを移動させる。

作成ファイル(雛形)

base_api_controller.rb

base_api_controller.rb
class Api::V1::BaseApiController < ApplicationController
end

各controller

module Api::V1
  class ArticlesController < BaseApiController

    def index
      articles = Article.all
      render json: articles
    end

    def show
      @article = Article.find(params[:id])
      render json: @article
    end
  end
end

ルーティングの設定

routes.rb
Rails.application.routes.draw do
  namespace :api, format: :json do
    namespace :v1 do
      resources :users
      resources :articles
    end
  end
end

ディレクトリの配置に合わせている感じ?

JSON の出力方法を設定

config/initializers/active_model_serializers.rbの作成

ファイルは自作

config/initializers/active_model_serializers.rb
ActiveModel::Serializer.config.adapter = :json_api

data がついて出力されるようになる。

使い方

関連ファイルを作成するコマンドの実行

$ be rails g serializer ControllerName

上記のコマンドで、 app ディレクトリ配下に serializers ディレクトリが自動で作成され、指定したモデル名のファイルが作成される。
それに詳細を記述していく。

class UserSerializer < ActiveModel::Serializer
  attributes :id,:name,:email,:password  出力したい key

  has_many :articles  リレーション関係 〇〇.rb そのままでオケ
end

参照

https://qiita.com/yuta-ushijima/items/d503addc7c5061ff3c6b#_reference-dd11c4dea4bc2078de0d

https://qiita.com/k-penguin-sato/items/adba7a1a1ecc3582a9c9

http://yu0105teshi.hateblo.jp/entry/2018/03/23/151725

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