ruby – ActiveModel :: Serializer :: CollectionSerializer

我正在使用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"}
]

我尝试过以下方法:

控制器:

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.这就是我的选择:

控制器:

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需要它.

点赞