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.
-
1Using erb? using Rails? tag it accordingly.tokland– tokland2011年12月04日 12:19:26 +00:00Commented Dec 4, 2011 at 12:19
4 Answers 4
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});" %>
4 Comments
account_ids.length should return 1 if it's value is [2])var obj = { key1: <%= @array.to_json %> }; I get: SyntaxError: illegal character key1: [\"dog\",\"cat\"], with an arrow pointing to the first slash. But raw() works: var obj = { key1: <%= raw @array %> };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.
3 Comments
raw(ruby array) works fine for me, transforming array Ruby to Array Javascriptvar obj = {key1: <% raw @array %> };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(", ") %>];
Comments
based on the last solution proposed by @Shadwell, i prefer something like:
var myJSArray = new Array("#{@my_array.map(&:inspect).join(", ")}");
my example doesn't use ERB, because it was used on a MapReduce function for mongodb.