Using Serializers with ruby on rails

Tor Francis - Jan 26 '23 - - Dev Community

If you've ever wanted to want to have your data return specific kinds of data from different paths using Active Record with out having to write a lot of extra code serializers are the solution. They provide a way of reacting a custom json object.

This is what our data looks like now:

{
  "id": 1,
  "title": "Top Gun",
  "year": 1986,
  "length": 154,
  "summary": "As students at the United States Navy's elite fighter weapons school compete to be best in the class, one daring young pilot learns a few things from a civilian instructor that are not taught in the classroom.",
  "poster_url": "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.imdb.com%2Ftitle%2Ftt0092099%2F&psig=AOvVaw0uR8BYBdnNmkTirteXeQzJ&ust=1674849371237000&source=images&cd=vfe&ved=0CA8QjRxqFwoTCIj9-Z6C5vwCFQAAAAAdAAAAABAE",  
  "created_at": "2022-05-21T13:12:35.682Z",
  "updated_at": "2022-05-21T19:11:11.682Z"
}
Enter fullscreen mode Exit fullscreen mode

use the command below to have it installed in the gem file

gem 'active_model_serializers'
Enter fullscreen mode Exit fullscreen mode

Once you run a bundle install then run:

rails g serializer model_name
Enter fullscreen mode Exit fullscreen mode

it gets created in #app/serializers/model_name_serializer.rb

class ModelNameSerializer < ActiveModel::Serializer
  attributes :id, :title, :year, :length, :director, :description, :poster_url, :summary

end
Enter fullscreen mode Exit fullscreen mode

after the serializer is created, it should now look like this:

{
  "id": 1,
  "title": "Top Gun",
  "year": 1986,
  "length": 154,
  "summary": "As students at the United States Navy's elite fighter weapons school compete to be best in the class, one daring young pilot learns a few things from a civilian instructor that are not taught in the classroom.",
  "poster_url": "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.imdb.com%2Ftitle%2Ftt0092099%2F&psig=AOvVaw0uR8BYBdnNmkTirteXeQzJ&ust=1674849371237000&source=images&cd=vfe&ved=0CA8QjRxqFwoTCIj9-Z6C5vwCFQAAAAAdAAAAABAE"  
}
Enter fullscreen mode Exit fullscreen mode

If you wanted to u wanted to create a custom method to return specific data based on what you have now, you could say:

def MovieCaption
  "#{self.object.title} - #{self.object.description}..."
end
Enter fullscreen mode Exit fullscreen mode

and add that method to the attributes to return.

If you had an array of objects you have specify which serializer to use:

render json: movies, each_serializer: ModelNameSerializer, status: :ok
Enter fullscreen mode Exit fullscreen mode

Something to be mindful is that serializers override when you want to specify what you return in the controller.

Here is a link to the Docs to read more on it.

Thank you.

. . . . . . .