Active Model Serializer和多个元值

时间:2013-08-29 00:17:28

标签: ruby-on-rails-3 active-model-serializers

我正在查看Active Model Serializer的README并看到这个例子:

render json: @posts, serializer: CustomArraySerializer, meta: {total: 10}, meta_key: 'meta_object'

...

{
  "meta_object": { "total": 10 },
  "posts": [
    { "title": "Post 1", "body": "Hello!" },
    { "title": "Post 2", "body": "Goodbye!" }
  ]
}

但我希望能够输出:

{
  "meta_object": { "total": 10 },
   "sort":[2,1],
  "posts": [
    { "title": "Post 1", "body": "Hello!" },
    { "title": "Post 2", "body": "Goodbye!" }
  ]
}

我猜我需要有两个元对象。这可能吗?我该怎么做?

1 个答案:

答案 0 :(得分:0)

正常的解决方案是将“sort”键本身嵌套在“meta”键下(“meta”是不是模型的响应信息的全能位置)。所以你会使用:

render json: @posts, serializer: CustomArraySerializer, meta: { total: 10, sort: [2, 1] }, meta_key: 'meta_object'
...
{
  "meta_object": {
    "total": 10,
    "sort": [2, 1]
  },
  "posts": [
    { "title": "Post 1", "body": "Hello!" },
    { "title": "Post 2", "body": "Goodbye!" }
  ]
}

如果您的要求绝对需要“排序”键出现在根目录,您可以手动执行:

response_json = CustomArraySerializer.new(@posts).as_json.merge { sort: [2, 1] }
render json: response_json, meta: { total: 10 }, meta_key: 'meta_object'
...
{
  "meta_object": {
    "total": 10
  },
  "sort": [2, 1],
  "posts": [
    { "title": "Post 1", "body": "Hello!" },
    { "title": "Post 2", "body": "Goodbye!" }
  ]
}