Domanda

I have an array of JSON in my Rails App in this format using Active Model Serializer:

[
  {
    "contact" : {}
  },
  {
    "contact" : {}
  }
]

How do I make it so that I remove one level of node above the contact USING active model serializer like this:

[
 {
 },
 {
 }
]

I also want to remove the node name "contact".

È stato utile?

Soluzione

This was covered in RailsCast #409 Active Model Serializers.

In order to remove the root node, you add root: false in the call to render in your controller. Assuming your contacts in JSON come from a contacts#index method, your code may look something like:

def index
  @contacts = Contacts.all
  respond_to do |format|
    format.html
    format.json { render json: @contacts, root: false }
  end
end

Or, if you don't want any root nodes in any of your JSON, in your ApplicationController, add the following method:

def default_serializer_options
  {root: false}
end

Altri suggerimenti

For people using ActiveModel::Serializer v0.10.x, you will need to create an initializer and include the following:

# config/initializers/serializer.rb
ActiveModelSerializers.config.adapter = :json
ActiveModelSerializers.config.json_include_toplevel_object = true

Then, just restart your app and you should get the root objects you desire.

This works in Rails 5.1.x. YMMV. HTH.

Usually the root node has the name of your controller by default if I am not wrong.

format.json { render json: @contacts}

Of course you need to remove root false, it removes the node's name.

If you want contact as root object use this:

format.json { render json :@contacts, :root => 'contact' }

/config/initializers/serializer.rb

ActiveModelSerializers.config.adapter = :json_api # Default: `:attributes`

By default ActiveModelSerializers will use the Attributes Adapter (no JSON root). But we strongly advise you to use JsonApi Adapter, which follows 1.0 of the format specified in jsonapi.org/format.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top