How to Render Custom JSON Responses with Active Model Serializer
Tags: ruby, rails, beginners, webdev
Published: 2023-07-26 19:00:43

<code>ActiveModel::Serializer</code> 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 <code>belongs_to</code> and <code>has_many</code> 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

```ruby
# Gemfile
gem 'active_model_serializers'
```
Then run <code>bundle i</code> to install the gem.

###Using AMS

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

```ruby
rails g serializer user
```

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 <code>UserSerializer</code> in the <code>app/serializers</code> directory.

Our new serializer might look something like this:

```ruby
class UserSerializer < ActiveModel::Serializer
    attributes :id

end
```

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

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

end
```

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

```ruby
class User < ApplicationRecord

    def num_of_trails
        self.trails.count
    end

end
```

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

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

end
```

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

###Rendering Associated Data

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

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

end
```

All of this avoids having to call <code>.to_json</code> 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 <code>app/serializers</code>. In this case, let's create one called <code>user_trail_serializer.rb</code>, and then move our custom <code>num_of_trails</code> 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 <code>trails.count</code> as follows:

```ruby
class UserTrailSerializer < ActiveModel::Serializer
  attributes :num_of_trails

  def num_of_trails
    self.object.trails.count
  end

end
```

To use our num_of_trails method, we need a new route in <code>routes.rb</code>

```ruby
get '/users/:id/num_of_trails', to: 'users#num_of_trails'
```
Then we need to add a <code>num_of_trails</code> action to our <code>UsersController</code> like so:

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

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

```json
{
    "num_of_trails": 4
}
```

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

```ruby
# 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
```

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

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

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

```

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

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

    has_many :reviews
    has_many :trails, serializer: CustomTrailSerializer

end
```

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.