3

I'm trying to turn a ruby array into a js array in a js.erb file. I've checked all questions on this in stack overflow but it isn't working for me.

Here is the function

  function c(c) {
   js_array = <%= raw @keys.to_json %>;
   b.selection.remove(), b.html.insert('js_array[0]');
    }

It throws the error Uncaught TypeError: Cannot read property '0' of null

Im still learning js so im not sure what is going wrong here

The ruby @keys array defiantly has data in it because I'm printing that on the same page.

And if i change the array to js_array = ['gwfe', 'efw', 'efwe']; it works fine. This makes me believe something is going wrong when trying to convert the ruby array into a js array.

2 Answers 2

4

After converting the array to JSON, you just need to mark it as HTML safe so it will render Javascript code.

This will do the trick:

<%= @keys.to_json.html_safe %>
Sign up to request clarification or add additional context in comments.

Comments

1

I assume, you are gettings @keys data from db or local. Could you try gon gem to pass the values from ruby to js. Here is the railscast tutorial for the same: http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

And see, if that works.

Let me know.

12 Comments

Changed it to js_array = <%=raw @keys.to_a%>; and it still doesn't work.
Could you, pass me the print output for @keys.to_a and try removing raw from the print?
Could you try this and see this as well js_array = <%=escape_javascript @keys.to_json %> ?
Well, that is an extra step which I feel is un-necessary. Can you move the js function from erb file to your rails view and see how it goes? The one which contains escape js.
Might as well, look into this as well. railscasts.com/episodes/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.