使用 ActiveModel::Serializer 序列化具有属性的数组/关系 [英] Serialize array/relation with attributes using ActiveModel::Serializer

查看:28
本文介绍了使用 ActiveModel::Serializer 序列化具有属性的数组/关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Active Model Serializers 序列化关系,并且我想为此关系设置一些全局"属性(例如计数):

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: [{}, {}, {}, ...]
  }
}

我怎么能这样做?

推荐答案

在控制器中的渲染调用期间,您可以传入 meta 属性.

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

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

这将产生以下 JSON:

This will produce the following JSON:

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

您可以通过传入 meta_key 选项来重命名元键名称.

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

这篇关于使用 ActiveModel::Serializer 序列化具有属性的数组/关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆