ActiveModel :: Serializer :: CollectionSerializer

I am using Serializer Active Model v0.10.0.rc4

I want to create json that looks like this:

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

I know the main thing:

render json: posts, each_serializer: PostSerializer

will create json like this:

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

I tried to do the following:

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

But it calls json like this:

{
  "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
}

Does anyone know how I can achieve the desired circuit?

+4
source share
2 answers

In the end I did not use CollectionSerializer. Here's what I went with:

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

Setting the adapter jsonensured that the elements posthad the desired root root.

Although I understand that having the root node specified for the elements of the array may not be normal, this is necessary for this api.

+2

JSON, , , JSON API. active_model_serializers, JsonApi. :

ActiveModelSerializers.config.adapter = :json_api
0

All Articles