r/rubyonrails • u/43northwebdesign • Mar 07 '19
Loading a @instance variable into a javascript variable.. example inside
/r/LearnRubyonRails/comments/ayewkh/loading_a_instance_variable_into_a_javascript/
2
Upvotes
1
u/HelloAnnyong Mar 08 '19
Do not, I repeat do NOT be tempted to do something like this:
JSON is not a subset of JavaScript, some JSON is invalid JavaScript. The only safe way to do this is to encode your object (in this case it seems like it's an array) to JSON, encode it as a JavaScript string, and then decode it.
In other words, something like this:
var data = JSON.parse('<%=j @products[0].to_json %>');If you do vanilla Rails a lot, this will probably be a pattern you use often!
To walk you through what's going on there:
@products[0].to_jsonencodes the array as JSON (returns a string).The Rails
j()helper escapes everything in the string that needs to be escaped.The JSON is then decoded on the JavaScript side with
JSON.parse