Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active model serializer each_serializer vs serializer

I have noticed when I want to fetch the collection of objects (@user.all) I have to user each_serializer

render json: @users, root: 'data', each_serializer: User::ShowSerializer

whereas when I have to have a single object show action serializer works.

render json: @user, root: 'data', serializer: User::ShowSerializer

Please can anyone explain the difference between the two

like image 755
Manav Avatar asked Dec 03 '18 03:12

Manav


1 Answers

Think of it as the each iterator in Ruby.

When you have a single record @user, no iteration is required, and in return you get a single serialized resource. Here we directly apply a serializer:

render json: @user, root: 'data', serializer: User::ShowSerializer

Think of this as the same as

User::ShowSerializer(@user)

When you have a collection of records, such as @user.all, you have to iterate over each resource to get a serialized collection of records. Here we apply each_serializer:

render json: @users, root: 'data', each_serializer: User::ShowSerializer

This is the same as

@users.each do |user|
  User::ShowSerializer(user)
end
like image 109
Pramod Shinde Avatar answered Sep 25 '22 02:09

Pramod Shinde