Active Model Serializers is a Rails gem that lets you change the way your data is shown in JSON format. When you request data from a Rails API endpoint, the answer is in JSON format and contains all of the ActiveRecord model’s properties, as well as any other models that go with it. However, in many instances, you may not need all of this information, and transferring needless data over the network can be wasteful.
Active Model Serializers let you choose how ActiveRecord models and other Ruby objects should be serialized. You can choose which traits and relationships to include, how the JSON output should look, and more. It also allows you to include metadata or URLs in the JSON answer.
To use active model serializers, you first need to install the gem and then create a serializer for your model. The serializer is a Ruby class that inherits from
ActiveModel::Serializer and specifies which attributes to include in the JSON output.
You can serialize the response by making use of the controller’s render function along with the :json parameter. This will cause the response to be serialized. In order to serialize the response, active model serializers will, by default, make use of the serializer that has the same name as the model.
An alternative to the default Rails serializers, Active model serializers provide more control over how your data is serialized and presented in JSON. Adding the following code to your Gemfile will make your Rails application compatible with active model serializers.
Next, issue the following command to generate a serializer for your model,
rails generate serializer <ModelName>
rails generate serializer post
This will create a serializer file for the specified model, located in the
app/serializers directory. In this file, you can define which attributes and associations to include in the JSON output using the
belongs_to methods. For example, if you have a
Post model and you only want to include the
body attributes in the JSON output, you could define the serializer as follows: