Using Serializers in Your Rails App

Active model serializers are a super important feature when retrieving data from your rails backend. They allow you to specify and customize the data from your models. You can explicitly express attributes and relationship data through your serializers which is extremely useful. In this blog I am going to show you an example of working with serializers to extract data from the backend.

Image for post
Image for post

Here is an example of a serializer for an event model. As you can see I list out the attributes that I will be using on the front side of the application.

Image for post
Image for post

As you can see here. After my initial fetch to my database to grab all of the event instances, this is what one instance looks like. An object with keys representing all the attributes I established in the serializer, pretty cool right?

Something even cooler is that you can send relationship data through the serializers as well. As you saw I established that events had many attending users in the first screenshot. Attending users comes from the relationship through the join table(users).

Image for post
Image for post

As you can see if we open of the attending users array we have a list of user objects who are attending the event. SO HELPFUL! Hopefully you can use this as a quick help when using serializers in the future!

For more help!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store