Question

I want to serialize relation using Active Model Serializers and I want to set some 'global' attributes (e.g. count) for this relation:

{
  users: {
    total: 12,
    page: 2,
    users: [{}, {}, {}, ...]
  }
}

How could I do that?

Was it helpful?

Solution

During your render call in the controller, you can pass in the meta attribute.

render @users, :each_serializer => UserSerializer, :meta => { :total => @users.count }

This will produce the following JSON:

{
  "users" : [...],
  "meta" : {
    "total" : 12
  }
}

You can rename the meta key name by passing in the meta_key option.

OTHER TIPS

You can define calculated properties in your serializer:

class FooSerializer < ActiveModel::Serializer
  attributes :users_count
  has_many :users

  def users_count
    object.users.size
  end
end

This will not make multiple DB calls for count as pointed out by @rmcsharry

 { 
    data: ActiveModelSerializers::SerializableResource.new(
            @users, each_serializer: UserSerializer).as_json,
    count: @users.count 
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top