Rails 3.1 include_root_in_json

ActiveRecord::Base.include_root_in_json = true doesn't seem to work in rails 3.10.rc4, and I don't see it in the docs.

Since the root element is now disabled by default, how to enable it again?

@comments.to_json in rails 3.1 now looks like

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

And in previous versions, it has the root root, which I need to return.

 [ { comment: { comment: "Fun street park.", created_at: 2011-06-29T02:28:29Z } } ] 
+6
ruby-on-rails ruby-on-rails-3
source share
3 answers

Try setting this right in your Comment model.

 class Comment < ActiveRecord::Base self.include_root_in_json = true end 
+8
source share

Turns out Rails 3.1 just creates this json configuration file for you. I did not know that this file was here, so my file in the initializers was ignored.

Ryan's answer above cancels this setting.

configurations / 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 
+15
source share

Also interesting is the params shell, new in rails 3.1:

ActionController :: ParamsWrapper

Wraps a parameter hash in a nested hash. This will allow clients to send POST requests without specifying any root elements.

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

+3
source share

All Articles