ruby-grape / grape-active_model_serializers

User active_model_serializers with Grape
MIT License
140 stars 68 forks source link

Array root documentation #81

Open stevelacey opened 7 years ago

stevelacey commented 7 years ago

Maybe I am missing the point... but I don't understand how, why or when the root option works – I am putting it in all sorts of places, on get/post, on namespaces/resources, on CollectionSerializer constructs... and it is never doing what I expect.

I am expecting root: 'users' to make the output:

{
  "users": [
    {
      "name": "steve"
    }
  ]
}

I see past issues that this changed at some point, is there documentation missing around this?

Also I found an issue from years ago that seemed to indicate root: false stopped working on collections at some point – that'd be handy too

Am I right in thinking that a CollectionSerializer with a root option doesn't realise that root until an Adapter handles it or something?

In a bunch of cases in the API I am working on we are returning CollectionSerializer instances from controller action, I've been toying with switching those to a render call – but that doesn't accept any options either

stevelacey commented 7 years ago

I am currently toying with patching a custom render_collection method onto Endpoint to achieve the functionality I want, would be good to get rid of this if there's a way:

module EndpointExtension
  def render_collection(resources, serializer:, root:)
    {root => ActiveModel::Serializer::CollectionSerializer.new(resources, serializer: serializer, scope: self)}
  end
end

Grape::Endpoint.send(:include, EndpointExtension)
drn commented 7 years ago

@stevelacey - can you check what your adapter is set to? The default AMS adapter is attributes, which ignores that root option. Perhaps you want to use the json adapter.

See https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/adapters.md for details.

You can override the default by adding ActiveModelSerializers.config.adapter = :json in an initializer.

stevelacey commented 7 years ago

Yeah it’s set to json On Wed, 8 Nov 2017 at 16:20, Darren Cheng notifications@github.com wrote:

@stevelacey https://github.com/stevelacey - can you check what your adapter is set to? The default AMS adapter is attributes, which ignores that root option. Perhaps you want to use the json adapter.

See https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/general/adapters.md for details.

You can override the default by adding ActiveModelSerializers.config.adapter = :json in an initializer.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/ruby-grape/grape-active_model_serializers/issues/81#issuecomment-342758044, or mute the thread https://github.com/notifications/unsubscribe-auth/AARq-33xRyKq2GSKhZ4y9J2vBDLUqjYOks5s0XJlgaJpZM4QI6hK .