草庐IT

ruby-on-rails - 事件模型序列化器 : Adding extra information outside root in ArraySerializer

coder 2025-05-20 原文

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

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 ?我想不通)。如何添加额外的根元素?

最佳答案

您可以将它们作为第二个参数传递给 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

在 Controller 中

render json: @user,  meta: { total: 10 }

关于ruby-on-rails - 事件模型序列化器 : Adding extra information outside root in ArraySerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20947266/

有关ruby-on-rails - 事件模型序列化器 : Adding extra information outside root in ArraySerializer的更多相关文章

随机推荐