Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby on rails

What are Serializers in ROR?

Talha Ashar

Serialization converts an object in memory into a stream of bytes that can be recreated when needed. Serializers in Ruby on Rails convert a given object into a JSONJavaScript Object Notation format.

Serializers control the particular attributes rendered when an object or model is converted into a JSON format.

The process is illustrated below:

Installation

To use a Serializer in your Rails project, you have to include the Serializer gem in your Gemfile, as shown below:

gem 'active_model_serializers'

To install the Serializer module, you will need to run the following command:

bundle install

Advantages

In Ruby on Rails, Serializers allow you to:

  • refactor code to avoid repetition
  • render multiple data models from a single controller
  • Specify which attributes to render

Usage

Consider a model, User, with a single attribute for its name. To generate a Serializer for this model, you need to run the following command:

rails g serializer user

The above command creates the file /app/serializers/user_serializer.rb with the following contents:

class UserSerializer < ActiveModel::Serializer
attributes :name
end

The attributes list informs the Serializer which particular attributes to render when an object is converted to the JSON format using the render: json command.

If, for instance, the User model also has attributes for age and company that require rendering, you can add these to the attributes list in the file as shown below:

class UserSerializer < ActiveModel::Serializer
attributes :name, :age, :company
end

Once this is done, you may visit the /user route of your Ruby on Rails project to view the JSON that is rendered.

Note: You can find a comprehensive guide on Serializers on the official Rails Documentation website.

RELATED TAGS

ruby on rails

CONTRIBUTOR

Talha Ashar
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring