Reputation: 755
I have an application, where I have an Array of elements on my controller. I want to pass this Array to a Javascript view, and then convert it to a JSON and parse it.
This is my View:
<% content_for :page_meta do %>
<script>
const filterItems = "<%= @filter_options %>";
const productItems = "<%= @mdms_products %>";
</script>
If I debug @filter_options. I have this on IRB:
@filter_options.class # => Array
And the value:
[{:name=>"Solution Type", :uid=>"application", :component=>"HierarchicalListFilter", :props=>{:rootUrl=>"/insulation/commercial/enclosure/applications", :rootText=>"Enclosure Solutions"}, :values=>[{:name=>"Walls", :slug=>"walls", :children=>[{:name=>"Framed", :slug=>"framed", :children=>[{:name=>"Steel Stud", :slug=>"steel-stud"}, {:name=>"Wood Stud", :slug=>"wood-stud"}]}, {:name=>"Masonry", :slug=>"masonry", :children=>[{:name=>"Concrete Masonry Unit", :slug=>"concrete-masonry-unit"}]}, {:name=>"Concrete", :slug=>"concrete", :children=>[{:name=>"Precast", :slug=>"precast"}, {:name=>"Tilt-up", :slug=>"tilt-up"}, {:name=>"Cast-in-place", :slug=>"cast-in-place"}]}, {:name=>"Metal Building", :slug=>"metal-building"},
Everything looks perfect right? But, on my javascript console debug, when I get the value of productItems I get this weird String:
[{:name=>"Solution Type", :uid=>"application", :component=>"HierarchicalListFilter", :props=>{:rootUrl=>"/insulation/commercial/enclosure/applications", :rootText=>"Enclosure Solutions"}, :values=>[{:name=>"Walls", :slug=>"walls", :children=>[{:name=>"Framed", :slug=>"framed", :children=>[{:name=>"Steel Stud", :slug=>"steel-stud"},
And of course, when I try to do a JSON.parse(filterItems) it shows a parse error.
So, Whats is the better way to pass an Ruby Array, to a Json in Javascript?
Upvotes: 1
Views: 34
Reputation: 211740
Ruby has a completely different notation than JavaScript, so you must express it in the proper form and ensure that it doesn't get HTML-escaped:
<script>
const filterItems = <%= @filter_options.to_json.html_safe %>;
const productItems = <%= @mdms_products.to_json.html_safe %>;
</script>
It may be easier to render out the whole thing as JSON and load it in via AJAX as well.
Upvotes: 1