1

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=&gt;&quot;Solution Type&quot;, :uid=&gt;&quot;application&quot;, :component=&gt;&quot;HierarchicalListFilter&quot;, :props=&gt;{:rootUrl=&gt;&quot;/insulation/commercial/enclosure/applications&quot;, :rootText=&gt;&quot;Enclosure Solutions&quot;}, :values=&gt;[{:name=&gt;&quot;Walls&quot;, :slug=&gt;&quot;walls&quot;, :children=&gt;[{:name=&gt;&quot;Framed&quot;, :slug=&gt;&quot;framed&quot;, :children=&gt;[{:name=&gt;&quot;Steel Stud&quot;, :slug=&gt;&quot;steel-stud&quot;},

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @tadman. On this specific case (i have a BIGGGGG amount of data on my session that i dont need to do async calls to server) it was only a Parsing problem. It worked as a charm. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.