我正在使用active_model_serializers呈现一个收集作为json进行ember-data custing。 渲染单个项目时,一切都很好,但收集渲染包括一个项目数组。

render json: @scenarios, status: :ok
.

给出:

[{"scenario":{"id":4,"name":"My sample scenario"}},{"scenario":{"id":5,"name":"Yet another sample scenario"}}]
.

但我想获得:

{"scenarios": [{"id":4,"name":"My sample scenario"},{"id":5,"name":"Yet another sample scenario"}]}
.

使用所有收集项,副数据等获取root密钥的艺术方式是什么?(文档不是那么清楚这个)

编辑

方案序列化器当前如下:

class ScenarioSerializer < ActiveModel::Serializer
  attributes :id, :name
end
.

有帮助吗?

解决方案

尝试最新版本。AMS使用控制器名称作为数组的键。默认情况下,它应该像上面所显示的那样呈现。

如果您的控制器未命名为场景,则可以强制如下所示的阵列的根元素:

render json: @scenarios, root: "scenarios", status: :ok
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top