Rails 3.1 include_root_in_json

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

尝试直接在Comment模型上设置此项。

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

事实certificate,Rails 3.1只是为你创建这个json配置文件。 我不知道这个文件在这里所以我的初始化程序文件被忽略了。

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

配置/初始化/ 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 

此外,引导3.1的新的params包装是有意义的:

ActionController的:: ParamsWrapper

将参数哈希包装到嵌套哈希中。 这将允许客户端提交POST请求,而无需指定任何根元素。

http://edgeapi.rubyonrails.org/classes/ActionController/ParamsWrapper.html