DEV Community

tartope
tartope

Posted on

Rails: A serializer for your serializer?

Getting used to serializers was tricky for me when I first learned of them. Then came custom serializers. 😑 I now think of them as a serializer for your serializer. Silly, I know. A custom serializer can be used to streamline the JSON data that is returned. Example: The models are director--< movies--< reviews. The return needs to be JSON data for director that includes the streamlined data for all movies of that director. Create a new serializer (DirectorMovieSerializer) and include only the attributes of movie that you want to be returned. Don't forget to add the has_many :movies relationship to your DirectorSerializer, and explicitly tell the DirectorSerializer to use the new serializer instead. See the code below:

DirectorSerializer:
Image description

Add DirectorMovieSerializer:
Image description

JSON data to be returned:
Image description

The JSON data returned should be the director data and the streamlined movie data. This made more sense to me when I started playing around with the code, so give it a try. 😀

Top comments (0)