2

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is the correct json structure for JSONAPI specification, so this is what you should return to comply with the spec - a meta attribute
Note that this does have the same database impact as the answer from @Stanislav if you trigger this code as a result of calling a parent serialiser (you will fire a count query for every parent). On very large datasets (probably millions of rows) this will get slow. Just sayin' :)
3

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

2 Comments

This works and is ok for small datasets. Just be aware that this will fire a user count query for every Foo. So when hitting foo/index route, if you return 100 foo's: one query to get the Foos followed by 100 "select count(*) from users where foo.id=x"
0

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 
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.