【问题标题】:Rails render json returning data as first attributeRails 渲染 json 作为第一个属性返回数据
【发布时间】:2017-01-10 07:12:36
【问题描述】:

我正在使用 REST API 调用 (get) 检索我的所有项目并返回一个 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

如何只返回每一行的属性?

【问题讨论】:

  • 你是否在你的应用中设置了 ActiveRecord::Base.include_root_in_json = "data"?
  • 我不是,应该在哪里设置?
  • 你在使用ActiveModelSerializers吗?该 JSON 看起来与 JSON API specification 格式完全一样。如果您使用的是 AMS,则应选择另一个适配器。 stackoverflow.com/questions/33620859/…
  • 就是这样,我正在使用 AMS,并且我已经制作了我相信的覆盖 AMS 的初始化程序配置。现在可以使用了,谢谢!
  • 很好,您可以自己发布问题的答案,以帮助遇到同样问题的其他人(并获得一些代表)。

标签: ruby-on-rails


【解决方案1】:

我会使用.as_json

class PeopleController < ApplicationController

  def index
    @people = Person.all

    render json: @people.as_json
  end
end

另外,如果我没记错的话,您当前的代码 render json: @people 将在幕后调用 .to_json默认情况下应该有 @987654325 @ 作为哈希的根......所以我会在你的代码中搜索.to_json,看看你是否在任何地方覆盖它......或者只使用.as_json

【讨论】:

  • 谢谢!他们都工作了,但奇怪的是我有另一个没有他们的应用程序,我只是看不出有什么不同
【解决方案2】:

问题是我使用的是 AMS,并且我已经做了这篇文章中解释的初始化配置:

Changing Active Model Serializers Default Adapter

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    相关资源
    最近更新 更多