简体   繁体   English

使用 ActiveModel::Serializer 序列化具有属性的数组/关系

[英]Serialize array/relation with attributes using ActiveModel::Serializer

I want to serialize relation using Active Model Serializers and I want to set some 'global' attributes (eg count) for this relation:我想使用 Active Model Serializers 序列化关系,并且我想为此关系设置一些“全局”属性(例如计数):

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

How could I do that?我怎么能那样做?

During your render call in the controller, you can pass in the meta attribute.在控制器中的渲染调用期间,您可以传入 meta 属性。

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

This will produce the following JSON:这将产生以下 JSON:

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

You can rename the meta key name by passing in the meta_key option.您可以通过传入meta_key选项来重命名元键名称。

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正如@rmcsharry 所指出的,这不会进行多次数据库调用以进行count

 { 
    data: ActiveModelSerializers::SerializableResource.new(
            @users, each_serializer: UserSerializer).as_json,
    count: @users.count 
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM