12

假设我有一个模型User和一个序列化UserSerializer < ActiveModel::Serializer器,以及一个如下所示的控制器:

class UsersController < ApplicationController
  respond_to :json
  def index
    respond_with User.all
  end
end

现在,如果我访问/users,我将收到如下所示的 JSON 响应:

{
  "users": [
    {
      "id": 7,
      "name": "George"
    },
    {
      "id": 8,
      "name": "Dave"
    }
    .
    .
    .
  ]
}

但是,如果我想在 JSON 响应中包含一些与任何特定用户都不相关的额外信息怎么办?例如:

{
  "time": "2014-01-06 16:52 GMT",
  "url": "http://www.example.com", 
  "noOfUsers": 2,
  "users": [
    {
      "id": 7,
      "name": "George"
    },
    {
      "id": 8,
      "name": "Dave"
    }
    .
    .
    .
  ]
}

这个例子是人为的,但它很好地近似于我想要实现的目标。使用活动模型序列化程序可以做到这一点吗?(也许通过子类ActiveModel::ArraySerializer化?我想不通)。如何添加额外的根元素?

4

4 回答 4

11

您可以将它们作为第二个参数传递给 respond_with

def index
 respond_with User.all, meta: {time: "2014-01-06 16:52 GMT",url: "http://www.example.com", noOfUsers: 2}
end

在 0.9.3 版中的初始化程序集中 ActiveModel::Serializer.root = true

ActiveSupport.on_load(:active_model_serializers) do
  # Disable for all serializers (except ArraySerializer)
  ActiveModel::Serializer.root = true
end

在控制器中

render json: @user,  meta: { total: 10 }
于 2014-01-06T10:03:28.913 回答
4

让它工作使用render

render json: {
  "time": "2014-01-06 16:52 GMT",
  "url": "http://www.example.com", 
  "noOfUsers": 2,
  "users": @users
}

问题是,这不调用UserSerializer,它只是调用.as_json每个单独的用户对象并跳过序列化程序。所以我必须明确地这样做:

def index
  .
  .
  .
  render json: {
    "time": "2014-01-06 16:52 GMT",
    "url": "http://www.example.com", 
    "noOfUsers": 2,
    "users": serialized_users
  }
end

def serialized_users
  ActiveModel::ArraySerializer.new(@users).as_json
end

不是最优雅的解决方案,但它有效。

于 2014-01-07T05:46:12.243 回答
0

如果您不想修改序列化程序或渲染,只需一个简单的技巧:

data = serializer.new(object, root: false)
# cannot modify data here since it is a serializer class
data = data.as_json
# do whatever to data as a Hash and pass the result for render
data[:extra] = 'extra stuff'
render json: data
于 2017-08-10T07:50:11.540 回答
0

只需在我的控制器中添加以下内容,我就可以让它适用于我的用例。AMS 0.10 不需要其他任何东西。

render 
    json: @user,  
    meta: {
        time: "2014-01-06 16:52 GMT", 
        url: "http://www.example.com", 
        noOfUsers: 2
    }
于 2018-01-28T18:29:08.327 回答