JSON output in Rails 2.1
I just came across a change in Rails 2.1 when converting an ActiveRecord object to JSON. The JSON output now includes the ActiveRecord model name in the object so if you have a user model and convert it to json, you get the following:
user = User.find(1)
user.to_json
{"user" : {"name" : "John Doe", "id" : 1}}This becomes a pain when you're pulling this data via AJAX and you're doing something like this:
def show
user = User.find(params[:id])
# to_json is called automatically so you don't need to call it explicitly
render :json => {:status => 'ok', :user => user}
endIn your client side code, you then have to type user twice, once for the hash key, and once for the ActiveRecord model name, to get to the user's attributes:
$.getJSON(url, function(json){
if (json.status == 'ok') {
// do something with user data
alert(json.user.user.name);
}
});Unnecessarily redundant and inconvenient. This seems to have been changed in Rails 2.1, but the old behavior can be restored by editing config/initializers/new_rails_default.rb and changing:
# Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = trueto
# Include Active Record class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = falseRestart your app, and you'll now get just the attributes for the model and not the model name.
Zach Waugh •