DEV Community

tartope
tartope

Posted on

Using Serializers in Rails

Serializers can be used to customize JSON data for a single model. However, they can also be used to handle associations between multiple models. The has_many and belongs_to Active Record macros can assist.

To use a serializer with a one-to-many association, add the belongs_to macro to the corresponding serializer. Example: there are three models, episode--< appearances >--guests. When the JSON data for appearances is returned, I want to include the data for episode and guest. Since the relationships have been established in the model, I can include the same has_one :episode and has_one :guest relationship in the corresponding serializer. Therefore, when the JSON data for appearance is returned, it will include the data for episode and guest.

Image description
Image description

The same can be used with many-to-many associations. Example: I want the JSON data to include guests along with data for episodes. Including the has_many :guests relationship in the corresponding episode serializer will return JSON data with the episode, and guests.

Image description
Image description

What helped me understand these concepts the most was seeing them in action. Practice coding different serializers to see the JSON data that is returned.

Top comments (0)