DEV Community

kirthinandi
kirthinandi

Posted on

What are Active Model Serializers?

Image description

Introduction

When creating a Rails API data structure, the process consists of setting up routes and controllers to take care of different requests and return the requested JSON. When returning this JSON, we can customize it to only display what we specifically want it to. There are various ways to show the information we want but the Rails' Active Model Serializer provides a simple way to customize JSON data while also following the "convention over configuration" technique.

Using the Active Model Serializer

In order to use the Active Model Serializer, you, first, need to install the gem in the Gemfile and activate it by running the command, 'bundle install', in your terminal.

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

Next, you need to create the ActiveModel::Serializer by running the command, 'rails g serializer ', in the terminal. Below is what the generated serializer would look like for a particular model, Restaurant.

# app/serializers/restaurant_serializer.rb
class RestaurantSerializer < ActiveModel::Serializer
  attributes :id
end
Enter fullscreen mode Exit fullscreen mode

Currently, the serializer is only allowing us to display the id of the specific restaurants in our data. If we want to customize the attributes being shown to the user, we can modify the serializer file by adding 'name, the year it started, cuisine, and a popular dish to the attributes.

class RestaurantSerializer < ActiveModel::Serializer
  attributes :id, :name, :year_started, :cuisine, :popular_dish
end
Enter fullscreen mode Exit fullscreen mode

Restaurants Controller

# app/controllers/restaurants_controller.rb
def show
  restaurant = Restaurant.find(params[:id])
  render json: restaurant
end
Enter fullscreen mode Exit fullscreen mode

Now, if we navigate to the localhost:3000/restaurants browser, we should we see all the restaurants listed including the attributes listed above.

Conclusion

You just learned how to create a serializer to display specific information for the user. With this knowledge, you can try creating a serializer on your own!

Top comments (0)