The Ruby Array is not being correctly passed to the Javascript layer

Recently, I encountered a scenario in my application where I needed to pass an Array of elements from my controller to a Javascript view. The goal was to convert this Array into JSON format and then parse it.

In the View section of my code, I included the following snippet:

<% content_for :page_meta do %>
    <script>
        const filterItems = "<%= @filter_options %>";
        const productItems = "<%= @mdms_products %>";           
    </script>

Upon debugging the @filter_options in IRB, I found that its class is Array and it contained the following data:

[{:name=>"Solution Type", :uid=>"application", :component=>"HierarchicalListFilter", :props=>{:rootUrl=>"/insulation/commercial/enclosure/applications", :rootText=>"Enclosure Solutions"}, :values=>[{:name=>"Walls", :slug=>"walls",

At first glance, everything seemed fine. However, upon checking my javascript console for the value of productItems, I noticed that the output was distorted with characters like &quot; and &gt;. This made parsing difficult as I encountered errors.

Therefore, I am seeking advice on a better approach to seamlessly pass a Ruby Array to a JavaScript JSON format. Any suggestions would be greatly appreciated.

Answer №1

Ruby and JavaScript use different notations, so it is important to write Ruby code correctly without HTML escaping:

<script>
  const filterItems = <%= @filter_options.to_json.html_safe %>;
  const productItems = <%= @mdms_products.to_json.html_safe %>;
</script>

Consider rendering the entire content as JSON and loading it through AJAX for simplicity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing multiple address parameters within a single-page application

Apologies for the lengthy post. I have encountered an issue with my code after running it through a bot that I can't seem to resolve. In my code, I aim to create functionality where you can visit the address #two, followed by two separate parameters ...

Forcing Reload of HTML5 Video to Avoid Caching Issues

Is there a way to instruct the HTML5 Video tag to stream the video chunks on demand/load without caching them on the client side? Essentially, how can I prevent the browser from storing the HTML5 video in its cache? My main objective is to have the video ...

Retrieving all array keys in PHP following a specific key

Recently, I encountered an array structure that looks like this: $ptJson = { ["phoneSMS1"]=> "mobile", ["phoneSMS2"]=> "mobile", ["phoneSMS3"]=> "mobile", ["phoneSMS4"]=> "mobile", ["phoneSMS5"]=> "main" } My task was t ...

Stretch out single column content vertically in bootstrap for a uniform look

I've been struggling to make multiple buttons vertically stretch to fit the container, but I can't seem to remember how I achieved this in the past. I have experimented with various options outlined on https://getbootstrap.com/docs/4.0/utilities/ ...

Are there any options to modify the default Bind timestamp format in the gin-gonic library?

Can someone help me with Go, specifically regarding gin-gonic and gorm? Let's consider a model like the one below // Classroom struct. type Classroom struct { gorm.Model Name string `json:"name"` Code string `jso ...

Finding the key name of a JSON object in BigQuery

I have a dataset in BigQuery with a column containing JSON strings. These JSON strings may include keys such as "person", "corp", or "sme". My goal is to write a query that can identify which of these keys exist in the JSON and store this information in a ...

What is the process for animating classes instead of ids in CSS?

My webpage currently features a setup similar to this. function wiggle(){ var parent = document.getElementById("wiggle"); var string = parent.innerHTML; parent.innerHTML = ""; string.split(""); var i = 0, length = string.length; for (i; i ...

Conceal items by clicking using raycasting technology

I'm trying to hide scene objects by clicking on them, but after following multiple tutorials on "raycaster", I'm having trouble identifying where the issue lies. When I open my HTML file, all the objects are hidden, even though I've removed ...

The jQuery scrollTop feature seems to be malfunctioning

My code is causing an error that I don't understand. Any help would be appreciated... I'm getting the following error message: Property does not exist on type '.js--section-plan'.ts(2339) when I hover over the offset() in vscode $(&apos ...

Jquery Banner Fade In animation malfunctioning

I am facing an issue with my banner on various browsers, especially IE 7,8, and possibly 9. When the fade-in effect is applied at the bottom of the banner, the shadows underneath turn black. Is there anyone who can help me resolve this issue? Website: ww ...

Serve HTML content with res.redirect() instead of changing the URL

I have a frontend code that makes a call to my backend using an XHR request. Here is the snippet of the code: var sendRequest = function(method, url, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readySt ...

Sending arguments from an NPM script to a NodeJS script

In my main script (publish-all.js), I am trying to call the npm publish script of an Angular project. This Angular project also has a sub-script (publish.js) that performs various tasks (creating folders, copying files, moving folders...) after running ng ...

Combine HTMLPlugin with react-chartjs-2 version 4

I'm attempting to implement a customized Label using a plugin with react-chartjs-2. Here are the versions I am currently using "chart.js": "^3.9.1", "react-chartjs-2": "^4.3.1", "chartjs-plugin-datalabels& ...

Retrieving Vue data from parent components in a nested getter/setter context

<template> <div id="app"> {{ foo.bar }} <button @click="meaning++">click</button> <!--not reactive--> <button @click="foo.bar++">click2</button> </div> </templ ...

Clear the local storage once the URL's view has been fully loaded

When retrieving details of a specific item by passing URL parameters stored in local storage, I encountered an issue. I need to delete the local storage variables after the view is loaded. However, what actually happens is that the local storage variable ...

The concept of circular dependencies in ES6 JavaScript regarding require statements

After transferring a significant amount of data onto the UI and representing them as classes, I encountered some challenges with managing references between these classes. To prevent confusing pointers, I decided to limit references to the data classes to ...

Using a Vue.js component within a traditional Rails modal

I am trying to incorporate a vuejs component into an existing bootstrap slim modal. Within the modal, I reference the container of the component as usual: form.slim = modal do = javascript_pack_tag 'product_asset', 'data-turbolinks-track& ...

Tips for transferring the ID from one element to another using JavaScript

I'm attempting to create a slideshow using icons all within one class. The "active" style class will have an ID and represent the current picture. By clicking either the left or right button, I aim to change the style of the active class. const l ...

Obtain the name of the checkbox that has been selected

I'm new to JavaScript and HTML, so my question might seem silly to you, but I'm stuck on it. I'm trying to get the name of the selected checkbox. Here's the code I've been working with: <br> <% for(var i = 0; i < ...

Is there a way to extract the value from JSON within logic apps?

Here is the JSON data I am working with: { "Price": { "For": "840.040", "From": "2.990" }, "ArticleNumber": "71151004", "ArticleNumberPartitionKey&qu ...