[英]ActiveModel::Serializer::CollectionSerializer
I'm using Active Model Serializers v0.10.0.rc4 我正在使用Active Model Serializers v0.10.0.rc4
I want to produce json that looks like this: 我想生成看起来像这样的json:
{
"posts": [
{ "post": {"id": 2, "name": "foo"} },
{ "post": {"id": 3, "name": "bar"} }
],
"next_page": 3
}
I know the basic: 我知道基本的:
render json: posts, each_serializer: PostSerializer
will produce json like this: 将产生这样的json:
[
{"id": 2, "name": "foo"}
{"id": 3, "name": "bar"}
]
I have attempted the following: 我尝试过以下方法:
controller: 控制器:
render json: posts, serializer: PostsSerializer
posts_serializer: 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
But this produces json like this: 但这会产生像这样的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
}
Anyone know how I can achieve the desired schema? 任何人都知道如何实现所需的架构?
In the end I didn't use CollectionSerializer
. 最后我没有使用
CollectionSerializer
。 This is what I went with instead: 这就是我的选择:
controller: 控制器:
render json: posts, serializer: PostsSerializer
posts_serializer: 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
Specifying the json
adapter ensured that the post
elements had the required root node. 指定
json
适配器可确保post
元素具有所需的根节点。
Whilst I appreciate that having a root node specified for array items may not be conventional, it was required for this api. 虽然我知道为阵列项指定根节点可能不是常规的,但是这个api需要它。
The JSON result you need is similar to that specified in the JSON API format. 您需要的JSON结果类似于JSON API格式中指定的结果。 To achieve this with
active_model_serializers
, you'll need to use the JsonApi
adapter. 要使用
active_model_serializers
实现此目的,您需要使用JsonApi
适配器。 You can specify this in the initializer file: 您可以在初始化文件中指定:
ActiveModelSerializers.config.adapter = :json_api
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.