将 "namespace" 添加到序列化程序

Add "namespace" to serializer

我的数据库中存在 User 模型,但是我想 return json 响应 active_model_serializers gem 其中 user 属性是 player 命名空间中的 encapsulated/nested,它在 db 中不存在(假设它是虚拟的,这是任意预期的响应)。

而不是:

{
    "email": "some@mail.com",
    "first_name": "Hey",
    "last_name": "Hoo",
    "birthdate": "1540-05-05",
    "phone_number": "856539571"
}

我想要:

{
    "player":
    {
        "email": "some@mail.com",
        "first_name": "Hey",
        "last_name": "Hoo",
        "birthdate": "1540-05-05",
        "phone_number": "856539571"
    }
}

在 UserSerializer class 中,定义根属性。例如:

class UserSerializer < ActiveModel::Serializer
  root :player

  ...
end

当 Nwocha 的回答正确时,我会添加更多细节。

至于documentation 说:

覆盖资源根仅适用于使用 JSON 适配器时。

通常,资源根是从被序列化的资源的 class 名称派生的。例如UserPostSerializer.new(UserPost.new) 将根据适配器集合复数化规则与根 user_postuser_posts 序列化。

在初始化程序 (ActiveModelSerializers.config.adapter = :json) 中使用 JSON 适配器时,或在渲染调用中传递适配器时,您可以通过将其作为参数传递给渲染来指定根。例如:

  render json: @user_post, root: "admin_post", adapter: :json

这将呈现为:


  {
    "admin_post": {
      "title": "how to do open source"
    }
  }

注意属性适配器(默认)不包括资源根。如果您使用 :json_api 适配器.

,您也将无法创建单个顶级根目录

之前提供的答案也有效,但最后我使用了稍微不同的方法。原来除了 player 应该还有另一个 json,比方说 team,这使得最终响应看起来像这样:

{
    "player": 
    {
        "email": "some@mail.com",
        ...
    },
    "team":
    {
        "name": "Fancy Team",
        ...
    }
}

我实际上做的是准确定义我想使用的 json,像这样:

class UserSerializer < ActiveRecord::Serializer
    attributes :player
    attributes :team

    def player
        {
            email: object.email,
            ...
        }
    end

    def team
        { 
            name: object.name,
            ...
        }
    end
end

如果我在 render json: 中使用 root 选项,整个序列化程序将被封装在这个名称中。很抱歉一开始没有清除它。