Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array to Javascript array

I have a Ruby array with account ids.

I would like to store the Ruby array of account ids in a Javascript array.

I was wondering the best way to do this?

In addition, when I've been trying to do this it seems that Javascript think if there is only one account id entered then that should be the size of the array. Is there a way around this? I've tried putting it in quotes but that does not seem to work.

like image 270
Brian Avatar asked Dec 04 '11 11:12

Brian


3 Answers

Let's assume you are using erb. A first approach:

<%= javascript_tag "account_ids = #{account_ids.to_json.html_safe};" %>

The problem is that this creates a global variable without context (who uses it?). That's why I'd rather call a function defined somewhere in your JS code:

<%= javascript_tag "setAccounts(#{account_ids.to_json.html_safe});" %>
like image 93
tokland Avatar answered Sep 28 '22 01:09

tokland


Here is the way works for me. Say I have array in controller:

@my_array = [['city', 'number'], ['nyc', 39], ['queens', 98]]

I want to use it in slim and generate a Google pie chart, Then I can get that JavaScript array in slim by:

javascript:
  var myJsArray = #{raw @my_array};

or I can get that JavaScript array in erb like:

var myJsArray = <%=raw @my_array%>;

Somehow, works for me.

like image 32
ken Avatar answered Sep 28 '22 01:09

ken


If in your controller you have:

@my_array = [1, 2, 3]

You can set a javascript variable like this in your view:

<script type="text/javascript">
  var myJSArray = new Array(<%= @my_array.map(&:to_s).join(", ") %>);
</script>

or:

var myJSArray = [<%= @my_array.map(&:to_s).join(", ") %>];

Both cases change your ruby array of numerical id values into an array of strings and then join those string values together with commas to output valid values for javascript.

If you want string representations in your javascript you'll need to add double quotes around the values in your ruby array:

var myJSArray = [<%= @my_array.map { |some_id| '"' + some_id.to_s + '"' }.join(", ") %>];
like image 44
Shadwell Avatar answered Sep 28 '22 01:09

Shadwell