#50 Rails API - Active Model Serializer

Summary

Using ActiveModel::Serializer, learn how to create the JSON responses for your Rails API application. ASM is a great object oriented approach to building a JSON API.
rails api json 7:53

Resources

Summary

# Gemfile
gem 'active_model_serializers'

# api/users_controller.rb
module Api
  class UsersController < ApplicationController
    before_action :set_user, only: [:show, :update, :destroy]

    def index
      @users = User.all
      render json: @users, each_serializer: UserSerializer
    end

    def show
      render json: @user #, serializer: UserSerializer
    end

    ...

  end
end

# app/serializers/application_serializer.rb
class ApplicationSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers
  default_url_options[:host] = 'api.demo.dev'
end

# app/serializers/user_serializer.rb
class UserSerializer < ApplicationSerializer
  attributes :id, :first_name, :last_name, :show
  attribute :email, if: :current_user
  attribute :edit_link, if: :current_user_is_owner
  has_many :phones

  def show
    UsersController.render(:show, assigns: { user: object}, layout: false ).squish
  end


  def edit_link
    edit_user_url(object)
  end

  def current_user_is_owner
    scope == object
  end
end

# app/serializers/phone_serializer.rb
class PhoneSerializer < ApplicationSerializer
  attributes :name, :phone_number
end