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
Serializers control the particular attributes rendered when an object or model is converted into a JSON format.
The process is illustrated below:
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
In Ruby on Rails
, Serializers allow you to:
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.
Free Resources