Serializers in Rails
YarixaR
Posted on September 11, 2022
I have finally reached the end of my boot camp, finishing my last code challenge with a high score. I'm feeling pretty good! Now I'm ready to talk about Serializers.
In the controller, we can customize JSON data to a specific model using include:
or .to_json(except: [:created_at, :updated_at])
. The include option will let us nest associated data in our response. Ideally, we don't want to give this responsibility to the Controller because it'll just make it "chunky" as they say. This is why we use Serializers.
Installing Serializers
To use serializers, you'll need to first check to see if this gem is already included in the Gemfile. If not, add gem 'active_model_serializers'
to the Gemfile. Then, bundle install.
Generating Serializer
In the console:
$ rails g serializer planet
The name of the serializer needs the same name as the model and written in lowercase.
After, this will generate an empty file that looks like this:
class PlanetSerializer < ActiveModel::Serializer
attributes :id
end
As you can see, it only has the attribute :id
. This will limit all of Planet
's data to show only the :id
in JSON format.
So let's go ahead and add Planet
's real attributes.
class PlanetSerializer < ActiveModel::Serializer
attributes :id, :name, :distance_from_earth, :nearest_star, :image
end
This way we don't have to add .to_json(except: [:created_at, :updated_at])
in our Controller and it can be exclusive to just communicating with models and views.
Serializing Relationships
Much like adding include:
in the controller, a serializer will let us nest associated data in our response. We already have associations in our models so we can put these relationships in the serializer too.
class MissionSerializer < ActiveModel::Serializer
attributes :id, :name
has_one :planet
end
class PlanetSerializer < ActiveModel::Serializer
attributes :id, :name, :distance_from_earth, :nearest_star, :image
has_many :missions
end
Sources:
- “Home.” Flatiron School, 9 May 2022, https://flatironschool.com/.
Posted on September 11, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.