Creating Custom API Data - Rails Serializer
You can add more than just ActiveRecord model attributes created in the database schema and associated models to the Rails active model serializer.
Background
The Travelogger site keeps track of trips. Users have many trips. And a trip belongs to a user.
The project uses a Rails backend API to send JSON data to the JavaScript frontend. You can serialize Rails data into a JSON format very easily with Active Model Serializer.
I want an individual trip to know it’s user’s total trip count. One method is to add the user and all of their trips to the single trip’s API data and have JavaScript count them. But that’s total overkill…
Custom API data can be created on the Rails side instead and then sent to JavaScript. Much nicer.
Requirements
- Set up the Rails general backend, especially models and associations.
- Add active_model_serializer gem.
- Generate serializers.
- Generate any explicit serializers.
Very Basic Set Up
Schema
Models
Serializers
Explicit Serializer
Custom API Data
Create a new function in your model that returns data.
Add the name of the new method to your attributes.
Another way is to create the new function in the serializer itself.
And that’s it! Super simple.
Conclusion
This is a great way to control exactly what info each API serves and how it can be accessed. API calls are minimized and streamlined.
Post by: Chely Ho