gpt4 book ai didi

ruby - ActiveModel::Serializer::CollectionSerializer

转载 作者:数据小太阳 更新时间:2023-10-29 07:18:18 27 4
gpt4 key购买 nike

我正在使用 Active Model Serializers v0.10.0.rc4

我想生成如下所示的 json:

{
"posts": [
{ "post": {"id": 2, "name": "foo"} },
{ "post": {"id": 3, "name": "bar"} }
],
"next_page": 3
}

我知道基本的:

render json: posts, each_serializer: PostSerializer

将生成这样的 json:

[
{"id": 2, "name": "foo"}
{"id": 3, "name": "bar"}
]

我尝试了以下操作:

Controller :

render json: posts, serializer: PostsSerializer

posts_serializer:

class PostsSerializer < ActiveModel::Serializer
attributes :posts, :next_page

def posts
ActiveModel::Serializer::CollectionSerializer.new(object,
each_serializer: PostSerializer,
root: "post"
)
end

def next_page
3
end
end

但这会产生这样的 json:

{
"posts": [
{
"object": {"id": 2, "name": "foo"},
"instance_options": {"each_serializer: {}", "root": "post" }
},
{
"object": {"id": 3, "name": "bar"},
"instance_options": {"each_serializer: {}", "root": "post" }
},
],
"next_page": 3
}

有人知道我如何才能实现所需的架构吗?

最佳答案

最后我没有使用CollectionSerializer。这就是我使用的:

Controller :

render json: posts, serializer: PostsSerializer

posts_serializer:

class PostsSerializer < ActiveModel::Serializer
attributes :posts, :next_page

def posts
object.map do |p|
ActiveModel::SerializableResource.new(p, adapter: :json)
end
end

def next_page
# todo
end
end

指定 json 适配器可确保 post 元素具有所需的根节点。

虽然我很欣赏为数组项指定根节点可能不是常规的,但此 api 需要它。

关于ruby - ActiveModel::Serializer::CollectionSerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068584/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com