Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 include_root_in_json

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

Since the root element is now off by default how do we re-enable it?

@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 node which I need to get back.

[
  {
    comment: {
      comment: "Fun street park.",
      created_at: 2011-06-29T02:28:29Z
    }
  }
]
like image 488
jspooner Avatar asked Jun 29 '11 03:06

jspooner


3 Answers

It turns out that Rails 3.1 just creates this json config file for you. I didn't know this file was here so my file in initializers was ignored.

In Ryan's answer above does override this setting.

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
like image 195
jspooner Avatar answered Nov 16 '22 12:11

jspooner


Try setting this directly on your Comment model.

class Comment < ActiveRecord::Base
  self.include_root_in_json = true
end
like image 44
Ryan Bigg Avatar answered Nov 16 '22 13:11

Ryan Bigg


Also, the params wrapper, new in rails 3.1, is of interest:

ActionController::ParamsWrapper

Wraps the parameters hash into a nested hash. This will allow clients to submit POST requests without having to specify any root elements.

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

like image 20
Woahdae Avatar answered Nov 16 '22 12:11

Woahdae