Rails API - Active Model Serializer

#50 Rails API - Active Model Serializer
10/16/2016

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.
6
rails api json

Summary

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
    end

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

    ...

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


  def edit_link
    edit_user_url(object)
  end

  def current_user_is_owner
    scope == object
  end
end
app/serializers/phone_serializer.rbclass PhoneSerializer < ApplicationSerializer
  attributes :name, :phone_number
end
142914?v=3&s=64
bf4 said 7 months ago:

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

635114?v=3&s=64
kobaltz said 7 months ago:

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