From Ruby array to JS array in Rails - "quote"?

I have a Ruby array like this in my controller:

@location_list = [ ['Mushrooms', 3], ['Onions', 1], ['Olives', 1], ['Zucchini', 1], ['Pepperoni', 2] ] 

And I find it like this in my opinion:

 location_list = "<%= @location_list.to_json %>"; 

But if I do an alert (location_list), I get:

 [[&quot;Mushrooms&quot;,3],[&quot;Onions&quot;,1],[&quot;Olives&quot;,1],[&quot;Zucchini&quot;,1],[&quot;Pepperoni&quot;,2]] 

How to get the corresponding object without these "quot

+7
source share
2 answers

Try:

 <%= raw @location_list.as_json %> 

Using to_json will render the string with embedded double quotes and will need to be escaped using JS. And it will be a string, not an array.

+25
source

This worked for me:

 <%= @location_list.to_s.gsub(''', '') %> 

Basically use .to_s to convert the entire array to a string, then use .gsub(''','') to remove quotes, replacing them with nothing.

-one
source

All Articles