Handling JSON in JS/ERB template in Rails 3

Michael Waxman picture Michael Waxman · Sep 21, 2010 · Viewed 23.6k times · Source

I have no trouble making typical AJAX calls to and from Rails(3) with JSON objects and jQuery-rails (jQuery library plus a special rails.js file).

In one controller, though, I want to RETURN some JSON in an erb template (create.js.erb) after an AJAX call.

I've tried every combination of things in the controller (@object.to_json, '[{"content":"hello world"}]', etc.) and in the template itself (JSON.parse(), single quotes, double quotes, etc.), but the object keeps on rendering like this:

'[{"groups":{},"created_at":"2010-09-21T03:49:34Z" ...

and as a result, my jQuery code cannot parse it and I get errors.

How do I need to prep my object in the controller, and what erb syntax do I need in the view for it to render as a valid JSON object?

Thanks so much!

Answer

alex.zherdev picture alex.zherdev · Sep 21, 2010

I'm not sure this is the cause, but you can also try playing around with html_safe method. ERB might be escaping your JSON because it thinks it's not html safe. Try calling that method when using the string:

@object.to_json.html_safe