I am trying to pass a ruby array to a js view (js.erb format) but it doesn't work at all.
var array = "<%= @publishers_list %>";
The variable array is just set as a string with all the array's values in it.
Is there a way to keep the array format ?
Edit
I just realized it was because of my array format.
[{:label => "name1", :value => value1}, {:label => "name2", :value => value2}]
I tried to pass a simple array like:
[1,2,3]
and it worked fine.
The question is now: how can I pass this kind of array ? I really need to keep these hashes in it because I want to put it as a source of a jQuery autocomplete.
I am trying to pass a ruby array to a js view (js.erb format) but it doesn't work at all.
var array = "<%= @publishers_list %>";
The variable array is just set as a string with all the array's values in it.
Is there a way to keep the array format ?
Edit
I just realized it was because of my array format.
[{:label => "name1", :value => value1}, {:label => "name2", :value => value2}]
I tried to pass a simple array like:
[1,2,3]
and it worked fine.
The question is now: how can I pass this kind of array ? I really need to keep these hashes in it because I want to put it as a source of a jQuery autocomplete.
Share Improve this question edited Apr 25, 2013 at 10:10 Mencls asked Apr 25, 2013 at 9:11 MenclsMencls 3392 gold badges6 silver badges15 bronze badges3 Answers
Reset to default 12var array = <%= escape_javascript @publisher_list.to_json %>
Try this:
var array = <%= j @publishers_list.to_json %>
j
is shorthand for escape_javascript
(thanks to commenter lfx_cool).
See the documentation: http://api.rubyonrails.org/classes/ERB/Util.html
To clean up your view code a little, you can also turn the @publishers_list
into json
in your controller. That way, in your view you can just use:
var array = <%= j @publishers_list %>
simply define a array in Controller's specific action like:
def rails_action
@publishers_list = []
# write some code to insert value inside this array
# like:
# @publishers.each do |publisher|
# @publishers_list << publisher.name
# end
end
js file which is associated with this action, like: rails_action.js.erb
now use your code
var array = [];
array = "<%= @publishers_list %>";
Thanks.