Tuesday, April 12, 2011

$.parseJSON with Rails 3's .to_json

This one stumped me for a bit today. If you had any old code from Rails 2.3.* and converted it to Rails 3.0.*, watch out for any instance variables in your controller that you call to_json on for processing by jQuery's $.parseJSON in your view.

Because the default in Rails 3 is to make all strings html safe, you no longer need to use the "h" helper method in your views. However, this means that code like this will no longer work:

controller: @temp = {:hello =>; "world"}
view: alert($.parseJSON("<%= @temp.to_json %>"))

You will get invalid JSON errors, because the "safe" string is not in a valid format for parseJSON. To solve this, use the Rails 3 html_safe helper to tell the view that this string is ok to send through as is:

controller: @temp = {:hello =>; "world"}
view: alert($.parseJSON("<%= @temp.to_json.html_safe %>"))