I'm trying to embed model data in some javascript in my RoR 4 app. The controller is generating JSON for the model data like so...
def my_controller_method
@person = Person.find(params[:id])
@person_json = @person.to_json(only: [:name, :id])
end
and I'd like to use that json in my unobtrusive javascript to create javascript objects using JSON.parse()...
var personJSON = <%= j @person_json %>;
var person = JSON.parse(personJSON);
but the javascript that's generated is...
var personJSON = {\"id\":1,\"name\":\"fred\"};
var person = JSON.parse(personJSON);
and the javascript is failing silently.
When searching for a solution, I found this question asked on SO, but when I try to use the html_safe method, my rails app crashes saying html_safe is an unknown method.
Thanks in advance for your help!
What about this:
var personJSON = <%= @person_json.to_json.html_safe %>
or
var personJSON = <%= raw @person_json %>
I think the last option is better for your particular case.
You need to escape the JSON with escape_javascript
:
var personJSON = "<%= escape_javascript @person_json %>";
You can also shorten this to:
var personJSON = "<%= j @person_json %>";
Works great on my rails 5.0
Controller
# foo.rb
@data = [{key1: 'value1', key2: 'value2'}, {key3: 'value3'}]
View
# foo.js.erb
var arr = JSON.parse("<%= escape_javascript(render(inline: @data.to_json)) %>")
console.log(arr) # (2) [Object, Object]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With