Using Serializer With Your Ruby on Rails API | by Ilolo Izu | Mar, 2022

Over the previous three weeks, I’ve been working instantly with Ruby on Rails studying the processes of making full-stack functions. Right this moment I’m going to write down on Lively Mannequin Serializers (AMS).

Serializers primarily gives a straightforward solution to customise how the JSON is rendered by our controllers.

The very first thing to do to make use of AMS is so as to add the gem to the gemfile.

# Gemfile
gem 'active_model_serializers'

After this, run bundle set up. The subsequent step within the course of goes to be so as to add the energetic mannequin serializer. Within the terminal, working …

rails g serializer serializer-name

will open and create one other serializer.

After this, navigating to the serializer folder below the app folder will lead us precisely the place we should be.

Now as an instance that we create a serializer referred to as UserSerializer.

This can be utilized on our consumer controller to get particular knowledge again, quite than having to prepare it later, we are able to do this now.

class UserSerializer < ActiveModel::Serializerattributes :id, :username, :password_digest, :is_admin
belongs_to :profile
has_many :feedback

It might look one thing like this. Right here the attributes are primarily going to be the components of the JSON that we need to embrace.

Now, Rails is definitely sensible sufficient to acknowledge that working a consumer serializer and consumer controller will work collectively, so there isn’t a level join the dots. How superior is that!? However, what occurs once we need to make our personal personalized serializer?

Nicely let me reply that query for you. We merely run that rails g serializer custom-serializer-name once more, acquire our attributes, and then add the serializer identify to our controller like this:

# app/controllers/movies_controller.rbdef abstract
film =[:id])
render json: film, serializer: MovieSummarySerializer

This small and simple performance can change into a game-changer once we attempt to manage knowledge. And simply while you assume it could not get any extra fascinating, wait till you hear all about nested serializers.

As my boot camp has taught me,

…We discovered that the ActiveModel::Serializer gem permits us to customise how we would like our JSON to be rendered with out sacrificing the Rails ideas of “conference over configuration” and separation of considerations.

More Posts