Ruby array for javascript - Rails

I am trying to pass a ruby ​​array to a js representation (js.erb format), but it does not work at all.

var array = "<%= @publishers_list %>";

An array of variables is simply set as a string with all the array values ​​in it.

Is there any way to save the format of the array?

Edit

I just realized that this is because of my array format.

[{:label => "name1", :value => value1}, {:label => "name2", :value => value2}]

I tried passing a simple array, for example:

[1,2,3]

and it worked fine.

The question now is: how can I pass this array? I really need to store these hashes in it because I want to express it as a jQuery autocomplete source.

+6
source share
3 answers
 var array = <%= escape_javascript @publisher_list.to_json %> 
+12
source

Try the following:

 var array = <%= j @publishers_list.to_json %> 

j is short for escape_javascript (thanks to escape_javascript commentator).

See documentation: http://api.rubyonrails.org/classes/ERB/Util.html

To clear the view code a bit, you can also include @publishers_list in json in your controller. Thus, in your opinion, you can simply use:

 var array = <%= j @publishers_list %> 
+2
source

just define an array in a specific Controller action, for example:

 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 associated with this action, for example: rails_action.js.erb

now use your code

 var array = []; array = "<%= @publishers_list %>"; 

Thanks.

0
source

Source: https://habr.com/ru/post/943603/


All Articles