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.
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});" %>
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.
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(", ") %>];
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