ActiveModel::Serializers
In this blog, we’ll discuss Ruby on Rails ActiveModel Serializers, what they do and how to use them to your advantage.
The Active Model Serializer provides an easy method to customize how the JSON rendered by our Controllers are structured. Active Model Serializers or AMS for short focus on a convention over configuration approach and is dependable on having separation of concerns.
Where to start with AMS?
The first order of business is to install Serializer gem either using our command line interface or by locating the Gemfile and adding the required gem there.
Once you have installed the gem, your gem file should read:
Next run “bundle install” to download all of the dependencies.
After this step is completed we will use our useful rails generator tool to create the Serializer file!
Enter “rails g serializer example-name” into your terminal and hit run.
You will see some changes take place within your VSCode (or other studio) files.
Open the app/serializers directory and located inside you should find the “example_name_serializer” that we’ve created!
Get Jacoby McCann’s stories in your inbox
Join Medium for free to get updates from this writer.
You should see a class that contains an attribute of :id, this is where the serializer magic starts to happen…
Now, to customize our JSON, we simply provide the list of attributes that we want included for use in our Controller.
Great! Now we can go back to our Controller and simplify our code.
No more .to_json, only:, include: and other methods to organize what we want to be rendered as JSON, our Serializer has already organized the specified information for us using our handy attributes!
AMS creates a very conventional based approach to serializing our various resources. So if we have an Example model, we can also have an ExampleSerializer, which, by default, Rails will use our Serializer if we simple called “render json: movie” in our controller.
Custom Methods
AMS allows us to customize information returned using an instance method on the specified Serializers class, such as in our ExampleSerializer. Say we want wanted to create a summary of a blog that consisted of the blogs title and the author that wrote the blog.
Within our Serializer class we will create a summary method, this instance will return an object attribute which will contain the first Example instance and “self.object.<attribute_name>” to access a specific attribute.
Lets create the summary method:
You should restart your rails server and navigate back to your localhost at this time to see our new summary added at the end of our JSON.
Thanks for reading this article about Active Model Serializers. I plan to come back at a later date to update this to go over how we can explicitly specify our serializer. I hope you enjoyed and stay tuned for the update to this blog!








