1
votes

I have an Active Model Serializer defined for my model and everything works fine when I call render json passing a single collection, like this:

render json: @collection

The problem is when I try to merge different attributes and collections, for example:

json_response = service.errors.merge(attribute1: value1)
render json: json_response.merge(collection1: @collection, collection2: @collection2)

When I do that, the collections does not use the defined Active Record Serializer. Instead, they just serialize all their attributes.

How can I ensure that when I do these merges, the serialization still uses the Active Record Serializer that I have defined for them?

1
What is service is it a database entry? - Tobias
No, it's a class that executes some calculations and is used as a variable inside the controller. - felipeecst

1 Answers

1
votes

You can serialize them directly before the render:

json_response = service.errors.merge(attribute1: value1)
render json: json_response.merge(
  collection1: ActiveModelSerializers::SerializableResource.new(@collection).as_json, 
  collection2: ActiveModelSerializers::SerializableResource.new(@collection2).as_json
)