0

出于某种原因,我的控制器创建的任何 json 都会生成一个 json 数组,但不会生成一个对象。我想知道它的行为是否正常?如果它我怎么能得到我正在寻找的东西。

这里的控制器

def index
  @articles = Article.all
  respond_to do |format|
    format.json  { render :json => @events }
  end
end

现在在这里我实际上得到了什么

[{"allday":true,"created_at":"2013-01-10T23:49:19Z","customer_id":1,"description":"A meeting tomorrow between Prime Minister","id":35}]

现在但是我想先看看这个对象,就像标准 json 一样

{ "Article":{"allday":true,"created_at":"2013-01-10T23:49:19Z","customer_id":1,"description":"A meeting tomorrow between Prime Minister","id":35}}
4

2 回答 2

1

您应该启用ActiveRecord::Base.include_root_in_json以全局获取所需的行为。从文档

该选项include_root_in_json控制 as_json. 如果为 true(默认值)as_json将发出以对象类型命名的单个根节点。例如:

user = User.find(1)
user.as_json
# => { "user": {"id": 1, "name": "Konata Izumi", "age": 16,
#               "created_at": "2006/08/01", "awesome": true} }

ActiveRecord::Base.include_root_in_json = false

user.as_json
# => {"id": 1, "name": "Konata Izumi", "age": 16,
#     "created_at": "2006/08/01", "awesome": true}

也可以通过将:root选项设置为false如下方式来实现此行为:

user = User.find(1)
user.as_json(root: false)
# =>  {"id": 1, "name": "Konata Izumi", "age": 16,
#      "created_at": "2006/08/01", "awesome": true}
于 2013-03-22T01:23:27.297 回答
1

您可以构建一个 ruby​​ 对象或哈希来反映您想要返回的 json 对象的结构并渲染它。

def index
  @articles = Article.all
  respond_to do |format|
    format.json  { render :json => @events.map { |e| { Article: e } } }
  end
end

这会给你类似的东西

[{ "Article":{"allday":true,"created_at":"2013-01-10T23:49:19Z","customer_id":1,"description":"A meeting tomorrow between Prime Minister","id":35}}]
于 2013-03-22T00:50:23.020 回答