Rails 3.1 include_root_in_json

6

ActiveRecord::Base.include_root_in_json = true 在rails 3.10.rc4中似乎无法正常工作,而且我在文档中也没有看到相关内容。

由于根元素现在默认关闭,我们如何重新启用它?

在rails 3.1中,@comments.to_json 现在的样子是:

[
  {
    comment: "Fun street park.",
    created_at: 2011-06-29T02:28:29Z,
  }
]

在之前的版本中,它有一个我需要找回的根节点。

[
  {
    comment: {
      comment: "Fun street park.",
      created_at: 2011-06-29T02:28:29Z
    }
  }
]
3个回答

15

原来Rails 3.1会为您创建这个JSON配置文件。我不知道这个文件在这里,所以我的initializers文件中的内容被忽略了。

Ryan在上面的答案中确实覆盖了这个设置。

config/initializers/wrap_parameters.rb

# Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.

# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActionController::Base.wrap_parameters :format => [:json]

# Disable root element in JSON by default.
if defined?(ActiveRecord)
  ActiveRecord::Base.include_root_in_json = false
end

8

尝试直接在您的Comment模型上设置此内容。

class Comment < ActiveRecord::Base
  self.include_root_in_json = true
end

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接