Rails将json作为第一个属性

时间:2017-01-09 19:29:00

标签: ruby-on-rails

我使用REST API调用(get)检索所有项目并返回json,这是控制器中的代码:

class PeopleController < ApplicationController

def index
  @people = Person.all

  render json: @people
end
end

它正在返回,但是有一个&#34;数据&#34;开头的字段:

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

如何只返回每行的属性?

2 个答案:

答案 0 :(得分: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 < / p>

答案 1 :(得分:0)

问题在于我使用AMS,并且我在本文中解释了初始化程序配置:

Changing Active Model Serializers Default Adapter

此配置覆盖了AMS,使JSON呈现原始输出,而不是序列化输出。