mike927
mike927

Reputation: 774

Rails - Serialize collection with additional field

I use 'active_model_serializers' as serialization engine. By now my index method returns array of orders. render json: @orders, each_serializer: Web::OrderSerializer. Now I want to add additional field next to array. It's orders quantity. As a result, I want something like:

{
  "order_quantity": 12,
  "orders": [(serialized collection here)]
}

How should I code that using Active Model Serializers syntax?

Upvotes: 1

Views: 444

Answers (1)

Ameena Shad
Ameena Shad

Reputation: 46

You can use #map here to get serialized value of each order.

render json: { 
  orders: @orders.map{|order| Web::OrderSerializer.new(order).attributes},
  order_quantity: @orders.count // 12
}

Upvotes: 1

Related Questions