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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With