1

I've got a controller that gets some data from the database and an html view is rendered nicely in my browser.

Now I need to bootstrap some json in my html (to be used by javascript).

I add the following code to render json in the controller:

@my_json = render_to_string(template: 'dimension_types/index.json.jbuilder')

I do nothing else, just add this code to my controller and what happens is that the browser now just shows my page's html code. In the html source my page is wrapped in <pre></pre> tags.

There's no error in the logs. I tried adding layout: false, passing various combinations of handlers and formats to render -- nothing changes.

What am I doing wrong? What part of the documentation am I missing?

phoet
  • 18,688
  • 4
  • 46
  • 74
vrepsys
  • 2,143
  • 4
  • 25
  • 37
  • Is the intention to render JSON instead of HTML ? Possibly the view handling is defaulting to HTML, instead of JSON – Grant Sayer Feb 11 '14 at 21:24
  • it finds the template successfully. As I said I tried format: :jbuilder etc. – vrepsys Feb 11 '14 at 21:28
  • That code wont render you JSON, it will render your JSON template into an instance variable and then render the regular HTML or whatever template it can find. You should either have a JSON typed template for the action OR do a render :json => ... in the action. – Tanel Suurhans Feb 11 '14 at 22:10
  • That's exactly what I want to do: render json into a variable – vrepsys Feb 11 '14 at 22:11
  • that should work, so what else do you do in your controller? – phoet Feb 12 '14 at 01:17
  • ok, I figured out that render_to_string changes the content type of the response to json -- thus the problem. Not sure what to do about it though. – vrepsys Feb 12 '14 at 08:48

1 Answers1

0

I also came across this problem. There might be a better way to do this, but here is a semi-hack that will work:

# the_controller.rb
def your_action
  #...
  @json_string = render_to_string(template: 'a_template', formats: [:json])
  # reset the content type header
  response.headers["Content-Type"] = 'text/html'
  #...
end

The next piece of code shows how I made use of the JSON string in my view. If the JSON contains user-generated data, you will want to more thoroughly sanitize it to prevent XSS security risk (more info: https://stackoverflow.com/a/10390313/111635). The JSON I am generating doesn't have this problem, so I just used html_safe:

# the_view.html.erb
# ... bunch of ERB code ...
<%= javascript_tag do %>
  $(document).ready(function() {
    do_stuff_with_json(<%= @json_string.html_safe %>);
  });
<% end %>
Community
  • 1
  • 1
Daniel Waltrip
  • 2,530
  • 4
  • 25
  • 30