0
0
Ruby on Railsframework~5 mins

Serializers (Active Model Serializers) in Ruby on Rails

Choose your learning style9 modes available
Introduction

Serializers help you control how your data is sent from your Rails app to the outside world. They make your data neat and easy to understand.

When you want to send only specific parts of your database records as JSON to a web client.
When you want to change the names or format of data fields before sending them.
When you want to include related data (like a user's posts) in the JSON response.
When you want to keep your controller code clean by moving JSON formatting elsewhere.
Syntax
Ruby on Rails
class ModelNameSerializer < ActiveModel::Serializer
  attributes :field1, :field2, :field3

  belongs_to :related_model
  has_many :other_related_models

  def custom_field
    # custom logic here
  end
end

The attributes line lists the fields to include in the JSON output.

You can add methods to create custom fields in the JSON.

Examples
This sends only the user's id, name, and email in the JSON.
Ruby on Rails
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email
end
This includes the post's fields and the user who wrote it.
Ruby on Rails
class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :body
  belongs_to :user
end
This changes the price field to show a dollar sign before the number.
Ruby on Rails
class ProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :price

  def price
    "$#{object.price}"
  end
end
Sample Program

This serializer sends the book's id, title, and the name of its author as a custom field. The controller renders the book as JSON using this serializer automatically.

Ruby on Rails
class BookSerializer < ActiveModel::Serializer
  attributes :id, :title, :author_name

  def author_name
    object.author.name
  end
end

# In controller
class BooksController < ApplicationController
  def show
    book = Book.find(params[:id])
    render json: book
  end
end
OutputSuccess
Important Notes

Active Model Serializers automatically picks the right serializer if named properly.

Keep serializers simple and focused on formatting data only.

You can nest serializers to include related objects easily.

Summary

Serializers format your Rails data into clean JSON.

They help you choose which fields to send and how to show them.

Use serializers to keep your controllers simple and your API consistent.