1

Given a partial view that simply turns a given ruby object into JSON, shouldn't render 'ajax/object' and render json: @object deliver the same result?

ajax/object.json.erb:

<%= @object.to_json %>

@object:

{&quot;id&quot;:1}

Because they don't.

render 'ajax/object' results in XMLHttpRequest.response === null and the rendered view being sent as: (Snippet taken from saved .har file)

      "content": {
        "size": 18,
        "mimeType": "application/json",
        "compression": -11,
        "text": "{&quot;id&quot;:1}"
      },

render json: @object, on the other hand, results in the behavior I expected: XMLHttpRequest.response === ("id": 1)

So my question is: Is this difference in rendering behavior a bug and, if not, what is the purpose of render 'ajax/object''s rendering behavior?

Judah Meek
  • 565
  • 7
  • 16

1 Answers1

1

The issue here is that the string created in the template is HTML escaped.

While you could fix it with:

<%= raw( @object.to_json ) %>

Using a template is stupid and silly in the first place. Rails has to lookup the template by traversing a tree of possible files and then has to parse ERB and create a string buffer etc. This is just ridiculously inefficient for something which can be handled by passing an object to a JSON encoder.

max
  • 96,212
  • 14
  • 104
  • 165
  • If you want a slow JSON templating language there is always jBuilder. – max Jan 13 '17 at 23:04
  • Thanks for your answer. I realized that the template was inefficient and intended to change it. I just didn't understand why it didn't work at all. – Judah Meek Jan 13 '17 at 23:29
  • There's huge xss vulnerabilities possible with just converting an object to JSON on a web page. – justingordon Jan 15 '17 at 03:58
  • @justingordon how so? If you are just passing data from your controller to a view and calling `.to_json` on it there is no specific XSS vulnerability - you are doing the exact same thing as `render json: @object` but in a really convoluted way. – max Jan 15 '17 at 04:37