#50 Rails API - Active Model Serializer


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


Gemfilegem 'active_model_serializers'
api/users_controller.rbmodule Api
  class UsersController < ApplicationController
    before_action :set_user, only: [:show, :update, :destroy]

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

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


app/serializers/application_serializer.rbclass ApplicationSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers
  default_url_options[:host] = 'api.demo.dev'
app/serializers/user_serializer.rbclass 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

  def edit_link

  def current_user_is_owner
    scope == object
app/serializers/phone_serializer.rbclass PhoneSerializer < ApplicationSerializer
  attributes :name, :phone_number
bf4 said over 3 years ago on Rails API - Active Model Serializer :

I'm here due to the link from RubyWeekly. I haven't watched the video, only seen the notes, but as an ActiveModelSerializers maintainer, I'd ask if the various unusual decisions could be explained and if they should be something the library should handle.  For example: 1) mixing in the url helpers is not necessary 2) the show method in the serializer, besides violating separation of concerns, is very strange, and I'm not sure how it would be used 3) code is missing any configuration

kobaltz PRO said over 3 years ago on Rails API - Active Model Serializer :

Thanks for your work with the gem!

1. I tried omitting the URL Helpers on the --api version and ran into undefined method issues.  Also, the default_url_options also failed without the url helpers.

2. This definitely would be a very specific use case. It was more of an illustration that ASM does support rendering partials. 

3. Not sure I follow.

Login to Comment