Serialize array/relation with attributes using ActiveModel::Serializer

99封情书 提交于 2019-12-11 02:23:55

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/18570643/serialize-array-relation-with-attributes-using-activemodelserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!