DEV Community

Zoe Mendez
Zoe Mendez

Posted on

Ruby on Rails Serializers

Serializers

What is a Serializer?

ActiveModel::Serializers allows you to gather the information you wish to be rendered from the specific model. With the right relationships in place this can become the most amazing gem you come by in Ruby.

Image description

In my most recent project you can see I used my User Serializer to help create an image Url for an uploaded image. As well as rendered the pets that were correlated to the User. In the attributes section in the Serializer is where you choose what attributes from the given model you wish to display when rendering.

This allowed me to fetch my full user information without having to do multiple fetch request and doing a filter on the pets to compare the user id to the owner id that is in the pet model.

With the help of the Serializer, you can see above that I was able to design how the :featured_image element was being displayed in the fetch. I choose to do it that way, because if the image wasn't posted correctly it wouldn't add that attribute to the post request, which allowed me to render a default image in return.

You can use this in many different ways and I only began exploring how much you can do with Serializers. Can't wait to see what more I can learn

Top comments (0)