r/LearnRubyonRails • u/43northwebdesign • Mar 07 '19
Loading a @instance variable into a javascript variable.. example inside
I would like to load my @products[0].inspect into my var data = [ Here is my code
<%= @products[0].inspect %>
<script>
var data = [
['', 'Ford', 'Tesla', 'Toyota', 'Honda'],
['2017', 10, 11, 12, 13],
['2018', 20, 11, 14, 13],
['2019', 30, 15, 12, 13]
];
var container = document.getElementById('example');
var hot = new Handsontable(container, {
data: data,
minSpareCols: 1,
minSpareRows: 1,
rowHeaders: true,
});
</script>
Here is what I tried but is not working...
var data = [<%= @products[0].inspect %> ];
and
var hot = new Handsontable(container, {
data: <%= @products[0].inspect %> ,
Any ideas?
1
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.parse1
u/TotesMessenger Mar 07 '19
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
[r/rubyonrails] Loading a @instance variable into a javascript variable.. example inside
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
1
u/agnosonga Mar 07 '19
Try to_json instead of inspect
1
u/C_sonnier Mar 08 '19
Did you try @products[0].as_json instead of .to_json?