DEV Community

Cover image for Serializers in Rails
YarixaR
YarixaR

Posted on

Serializers in Rails

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Empty JSON data

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
Enter fullscreen mode Exit fullscreen mode

Planet data

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
Enter fullscreen mode Exit fullscreen mode
class PlanetSerializer < ActiveModel::Serializer
  attributes :id, :name, :distance_from_earth, :nearest_star, :image

  has_many :missions
end
Enter fullscreen mode Exit fullscreen mode

Nested missions

Sources:

Top comments (0)