1

I'm retrieving all my items with a REST API call (get) and returning a json, this is the code in the controller:

class PeopleController < ApplicationController

def index
  @people = Person.all

  render json: @people
end
end

It's returning, but with a "data" field at the beginning:

{"data":
   [
      {"id":"1","type":"people","attributes": {"name":"survivorTest","age":"55"}},
      {"id":"2","type":"people","attributes": {"name":"test666","age":"44"}},
      {"id":"3","type":"people","attributes": {"name":"test666","age":"6666"}}
   ]
}

This is my route:

Rails.application.routes.draw do
   resources :people
end

How can I return only the attributes from each row?

matheushf
  • 19
  • 4
  • Are you setting ActiveRecord::Base.include_root_in_json = "data" somewhere in your app? – Ryenski Jan 09 '17 at 20:01
  • I'm not, where should I set it? – matheushf Jan 09 '17 at 20:05
  • Are you using [ActiveModelSerializers](https://github.com/rails-api/active_model_serializers)? That JSON looks exactly like the [JSON API specification](http://jsonapi.org/) format. If you are using AMS, you should select another adapter. http://stackoverflow.com/questions/33620859/changing-active-model-serializers-default-adapter – max Jan 09 '17 at 20:09
  • 1
    That was it, I'm using AMS, and I've made the initializer configuration that was overriding AMS I believe. It's working now, thanks! – matheushf Jan 09 '17 at 20:13
  • Good, you can post an answer the question yourself to help others who have the same problem (and get some rep). – max Jan 09 '17 at 21:18

2 Answers2

0

I would use .as_json

class PeopleController < ApplicationController

  def index
    @people = Person.all

    render json: @people.as_json
  end
end

Also, your current code, render json: @people, if I remember correctly, would be calling .to_json behind the scenes, which by default should not have data as the root of the hash... so I would go search for .to_json in your code to see if you are overriding it anywhere... or just use .as_json

BigRon
  • 3,182
  • 3
  • 22
  • 47
  • Thanks! Both of them worked, but the strange part is that I have another application that works without them, I just can't see what is different – matheushf Jan 09 '17 at 19:46
0

The problem is that I'm using AMS, and I've made the initializer configuration explained in this post:

Changing Active Model Serializers Default Adapter

This configuration was overriding AMS, making the JSON render the original output, and not the serialized one.

Community
  • 1
  • 1
matheushf
  • 19
  • 4