Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array root documentation #81

Open
stevelacey opened this issue Oct 27, 2017 · 3 comments
Open

Array root documentation #81

stevelacey opened this issue Oct 27, 2017 · 3 comments

Comments

@stevelacey
Copy link

stevelacey commented Oct 27, 2017

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
Copy link
Author

stevelacey commented Oct 30, 2017

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
Copy link
Member

drn commented Nov 8, 2017

@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
Copy link
Author

stevelacey commented Nov 8, 2017 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants