Serializing JSON Data in Rails Using Custom Methods

Angelo Spampinato
3 min readJun 29, 2019

--

In this blog, I’ll walk you through a helpful tool with serialization using custom methods. I’m not going to walk through how to set up serialization from scratch, for a good guide on that check out Brenden Thornton’s article. Serialization allows us to nest data in our APIs, which is useful for myriad reasons, including reducing the amount of calls to the API for necessary data.

Schema

The example below is for a crowdfunding platform I built, I have a model for donations, and they belong to a campaign and a user. Here is the schema for the donations:

My schema

The donation table has an amount, a user id, a campaign id, and a message associated with it. My API isn’t showing all of this info however, due to serialization. When viewing the JSON data from my API I don’t see all of this information, only that which is included in my serializer file.

Serializer

Left: the donation serializer || Right: JSON response from my API

As you can see, the attributes in my serializer and what shows up as JSON in the response are mostly different for what shows up in my schema. This is because of custom methods that I’ve defined in my donation model, which enables me to access data from user and campaign that it belongs to.

Model

My Donation class

I’ve defined these methods to enable me to access information that I need to have when building my app, they can be anything though. campaign_title is giving me access to the title of the campaign that the donation is associated with, and campaign_owner is returning the name of the user that started the campaign the donation is associated with.

NOTE: The name of the custom method in the class file has to match the name of the attribute in the serializer.

NOTE: In this instance, calling campaign.title on line 14 in the image above is the same as calling self.campaign.title, Rails will automatically inject the self for you within a class.

Conclusion

Hopefully this helps save you time and energy when working with your API! It was a revelation for me when I realized I could reduce my back end calls greatly by advancing my serialization game.

--

--

Angelo Spampinato
Angelo Spampinato

No responses yet