Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Feb 23 ’12

Rails’ include_root_in_json

When rendering JSON from your controllers (or when using to_json directly), Rails 3.1 and above won’t include the root element in the output:

post = Post.first
# => #<Post id: 1, title: "My first blogpost" ...

post.to_json
# => "{\"id\":1,\"title\":\"My first blogpost\", ...}"

To include the root element (post in this example), set ActiveRecord::Base.include_root_in_json to true:

# wrap_paramters.rb
if defined?(ActiveRecord)
  ActiveRecord::Base.include_root_in_json = true
end

Result:

post.to_json
# => "{\"post\":{\"id\":1,\"title\":\"My first blogpost\", ...}}"

In version of Rails < 3.1, including the root element is the default. You can disable it by adding ActiveRecord::Base.include_root_in_json = false to one of your files in config/initializers or in application.rb/environment.rb directly.

More info in the API docs on ActiveModel::Serializers::JSON.

0 comments

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus