Articles by Sergio Xalambrí

Serialize list of items with ActiveModel::Serializer

Most of the them, when working on Rails with ActiveModel::Serializer you will do something like this:

render json: user, serializer: UserSerializer

Or if it's a list

render json: users, each_serializer: UserSerializer

This way, Rails will take care of calling your serializer with the item or calling each item on the list with the serializer.

What happens if you want to manually call them inside a list? You can do

render json: ActiveModel::Serializer::CollectionSerializer.new(
  users,
  serializer: UserSerializer
).as_json

This way you will tell ActiveModel::Serializer to call your serializer UserSerializer for a collection of items and use users as the data, so the gem will iterate the list of users and serialize them.