为每个方法设置活动模型序列化器适配器

Set Active Model serializer adapter per method

我正在尝试在 rails 中构建一个仅 api 的应用程序 5. 我正在使用活动模型序列化程序 (AMS)。 在我的 GET /users (UsersController#index) 端点上,我希望根 json 在 json 用户数组之前有一个 "users" 关键字。

如果我用 ActiveModelSerializers.config.adapter = :json 值设置初始化器,那么我就有了想要的行为。

但是,在 GET /users/1 上,简单用户 json 位于密钥 user 下。我想摆脱这个密钥(在这种情况下)并简单地回答用户 json 作为根 json.

问题是:如何在特定 endpoint/response/method 上定义 AMS 适配器?这可能吗?

我应该读过手册:$

要覆盖 "root" 键,您必须在调用 render 方法时提供一个 root: 参数。如果你在初始化器上使用 :json 适配器,它会像这样:

render json: @user, root: "admin" 这将生成一个 json 像这样:

{ "admin":{ "id": 123, "email": "email@example.com" } }

如果需要,您还可以在 root: 之后提供另一个键来设置适配器,如下所示:adapter: :json

因此,:attributes 适配器没有根密钥。为了删除根键,你可以这样做: render json: @user, root: "admin", adapter: :attributes

官方文档是here and here