Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make root node in Active Model Serializer

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".

like image 454
Madhan Avatar asked Mar 11 '13 23:03

Madhan


Video Answer


1 Answers

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
like image 82
Paul Fioravanti Avatar answered Sep 29 '22 13:09

Paul Fioravanti