2017-01-09 70 views
1

我取回我的所有項目使用REST API調用(獲得)並返回一個JSON,這是在控制器代碼:Rails的渲染JSON數據返回的第一個屬性

class PeopleController < ApplicationController 

def index 
    @people = Person.all 

    render json: @people 
end 
end 

它的返回,但與開頭「數據」字段:

{"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"}} 
    ] 
} 

這是我的路線:

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

我怎麼能只返回一個來自每一行的屬性?

+0

你在你的應用程序的某處設置ActiveRecord :: Base.include_root_in_json =「data」嗎? – mysmallidea

+0

我不是,我應該在哪裏設置它? – matheushf

+0

你使用[ActiveModelSerializers](https://github.com/rails-api/active_model_serializers)嗎?該JSON看起來完全像[JSON API規範](http://jsonapi.org/)格式。如果您正在使用AMS,則應選擇另一個適配器。 http://stackoverflow.com/questions/33620859/changing-active-model-serializers-default-adapter – max

回答

0

我會用.as_json

class PeopleController < ApplicationController 

    def index 
    @people = Person.all 

    render json: @people.as_json 
    end 
end 

而且,當前的代碼,render json: @people,如果我沒記錯的話,會調用.to_json幕後,默認情況下這應該data爲根的散列...所以我會去你的代碼中搜索.to_json,看看你是否覆蓋它在任何地方......或者只是使用.as_json

+0

謝謝!他們都工作,但奇怪的部分是,我有另一個應用程序沒有他們的作品,我只是看不到有什麼不同 – matheushf