DEV Community

Cody Barker
Cody Barker

Posted on

How to Render Custom JSON Responses with Active Model Serializer

ActiveModel::Serializer is a ruby gem that gives us the ability to customize the JSON responses we get from our controllers. This gem simplifies passing data from custom methods in our models, allows us to use our belongs_to and has_many macros to pass associated data, and even allows us to send different responses depending on the controller action triggered.

Installing AMS

To get started, we first need to add the gem to our Gemfile

# Gemfile
gem 'active_model_serializers'
Enter fullscreen mode Exit fullscreen mode

Then run bundle i to install the gem.

Using AMS

AMS comes with a generator which is great! In order to create a serializer for an example User model, run:

rails g serializer user
Enter fullscreen mode Exit fullscreen mode

AMS relies on 'convention over configuration', so when creating serializers, make sure their names are singular to match their model names.

We can find our new UserSerializer in the app/serializers directory.

Our new serializer might look something like this:

class UserSerializer < ActiveModel::Serializer
    attributes :id

end
Enter fullscreen mode Exit fullscreen mode

In order to customize the JSON response for a user, we can add or subtract any user attributes we like. For example:

class UserSerializer < ActiveModel::Serializer
    attributes: :id, :username, :city, :state

end
Enter fullscreen mode Exit fullscreen mode

AMS also makes it simple to pass data from custom methods in our models. Say we want to pass the total number of users. We could go to our User model and create a custom instance method to do that like so:

class User < ApplicationRecord

    def num_of_trails
        self.trails.count
    end

end
Enter fullscreen mode Exit fullscreen mode

Then we simply go back to our UserSerializer and add our custom method to the list of attributes.

class UserSerializer < ActiveModel::Serializer
    attributes: :id, :username, :city, :state, :num_of_trails

end
Enter fullscreen mode Exit fullscreen mode

That's it! Now our JSON response will include a user object with a property called num_of_trails.

Rendering Associated Data

So long as we have set up the correct Active Record associations in our models using belongs_to, has_many and has_many through macros, we can also include associated data in our user response by using those macros as well. For example, if a user has_many :reviews and also has_many :trails, through: :reviews, we can simply say a user has_many :trails and AMS will know what to do because of the has_many through macro in our model. The following would return a JSON object for the user with the attributes listed, as well as properties of reviews and trails, each of which would include an array of their corresponding associated objects.

class UserSerializer < ActiveModel::Serializer
    attributes: :id, :username, :city, :state
    has_many :reviews
    has_many :trails

end
Enter fullscreen mode Exit fullscreen mode

All of this avoids having to call .to_json in our controller actions, and the complicated nesting that comes with defining what to include in that response.

When we want to return different JSON responses depending on the controller action that is triggered, we can create custom serializers that don't follow the typical Rails naming convention.

To do this, we need to create a new file in app/serializers. In this case, let's create one called user_trail_serializer.rb, and then move our custom num_of_trails method from our User model into this serializer. It's important to note that when calling self in the serializer, the serializer will return an object, so from that object, we want to call trails.count as follows:

class UserTrailSerializer < ActiveModel::Serializer
  attributes :num_of_trails

  def num_of_trails
    self.object.trails.count
  end

end
Enter fullscreen mode Exit fullscreen mode

To use our num_of_trails method, we need a new route in routes.rb

get '/users/:id/num_of_trails', to: 'users#num_of_trails'
Enter fullscreen mode Exit fullscreen mode

Then we need to add a num_of_trails action to our UsersController like so:

# app/controllers/users_controller.rb
def num_of_trails
    user = User.find(params[:id])
    render json: user, serializer: UserTrailSerializer
end
Enter fullscreen mode Exit fullscreen mode

Now if you were to navigate to localhost:3000/users/1/num_of_trails, you would see an object with a num_of_trails property and the corresponding value. For example:

{
    "num_of_trails": 4
}
Enter fullscreen mode Exit fullscreen mode

If instead of returning the num_of_trails for a single user, we wanted to return an array of the counts for all users, we would need to create another route and action to do so.

# config/routes.rb
get '/user_trail_counts', to: 'users#user_trail_counts'

# app/controllers/users_controller.rb
def user_trail_counts
    users = User.all
    render json: users, each_serializer: UserTrailSerializer
end
Enter fullscreen mode Exit fullscreen mode

By using each_serializer: UserTrailSerializer, we're telling the action to use our UserTrailSerializer to render each of the users instead of our default UserSerializer.

By adding the :username attribute to our user__trail_serializer.rb file, we'll get an array of objects like this when visitng localhost:3000/user_trail_counts:

[
  {
    "username": "codybarker",
    "num_of_trails": 3
  },
  {
    "username": "kelliradwanski",
    "num_of_trails": 3
  },
  {
    "username": "benbuckingham",
    "num_of_trails": 3
  },
  {
    "username": "marvin",
    "num_of_trails": 0
  }
]

Enter fullscreen mode Exit fullscreen mode

We can also customize the JSON rendered from our associations, by creating and specifying custom serializers for our association macros. In our custom CustomTrailSerializer below, we could include whatever custom methods or attributes we'd like to render.

class UserSerializer < ActiveModel::Serializer
    attributes: :id, :username, :city, :state

    has_many :reviews
    has_many :trails, serializer: CustomTrailSerializer

end
Enter fullscreen mode Exit fullscreen mode

AMS is a wonderful gem that allows us to maintain separation of concerns, simplify the process of rendering data, and keep our code clean and readable for others, while you focus on what matters.

Top comments (0)