ActiveModelSerializer Basics in Rails 5

In this article, we will build a simple Rails 5 JSON API only app using active_model_serializers gem. Create a new Rails API only app.

rails new rapi --api

If you list middelware.

rake middleware

You will see:

use Rack::Sendfile
use ActionDispatch::Static
use ActionDispatch::Executor
use ActiveSupport::Cache::Strategy::LocalCache::Middleware
use Rack::Runtime
use ActionDispatch::RequestId
use Rails::Rack::Logger
use ActionDispatch::ShowExceptions
use ActionDispatch::DebugExceptions
use ActionDispatch::RemoteIp
use ActionDispatch::Reloader
use ActionDispatch::Callbacks
use ActiveRecord::Migration::CheckPending
use Rack::Head
use Rack::ConditionalGet
use Rack::ETag
use ActionView::Digestor::PerRequestDigestCacheExpiry
run Rapi::Application.routes

The API does not have the middelware that is included in Rails web app such as:

use Rack::MethodOverride
use WebConsole::Middleware
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash

In application_controller.rb:

class ApplicationController < ActionController::API
end

you can see it extends from ActionController::API class. Create an article scaffold.

rails g scaffold article title content 

Add active_model_serializers gem to Gemfile.

gem 'active_model_serializers'

and run bundle. Create a serializer for article model.

rails g serializer article

By default the generator only includes the id field. We can add other fields in the ArticleSerializer.

class ArticleSerializer < ActiveModel::Serializer
  attributes :id, :title, :content
end

Run the migration.

rails db:migrate

Add sample data in seeds.rb:

Article.create! title: "Superman", content: "Superman is a fictional comic book superhero appearing in publications by DC Comics, widely considered to be an American cultural icon..."
 Article.create! title: "Krypton", content: "Krypton is a fictional planet in the DC Comics universe..."
 Article.create! title: "Batman & Robin", content: "Batman is a fictional character created by the artist Bob Kane and writer Bill Finger...)"

Seed the database.

rails db:seed

Start the server.

rails s

Hit the articles index endpoint using curl.

curl http://localhost:3000/articles

You will see the json output.

 [{"id":1,"title":"Superman","content":"Superman is a fictional comic book superhero appearing in publications by DC Comics, widely considered to be an American cultural icon..."},{"id":2,"title":"Krypton","content":"Krypton is a fictional planet in the DC Comics universe, and the native world of the super-heroes Superman ..."},{"id":3,"title":"Batman \u0026 Robin","content":"Batman is a fictional character created ..."}]

The generated scaffold has index action that renders the list of all articles in json format.

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

You can download the source code for this article from rapi.

References


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.