Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Javascript code to create maps overlaid with data.

This is the existing code:

<h1>US Map of Startup Density</h1>

<% i = 0 %>

 <script type='text/javascript'>
   google.load('visualization', '1', {'packages': ['geochart']});
   google.setOnLoadCallback(drawMarkersMap);

   function drawMarkersMap() {
   var data = google.visualization.arrayToDataTable([
    ['Location', 'Startups'],
    <% @locations.count.times do %>
                [<%= "'#{@locations[i].name}', #{@locations[i].d_s}" %>],
         <% i += 1 ;end %>

 ]);

  var options = {
   region: 'US',
   resolution: 'provinces',
   displayMode: 'markers',
   magnifyingGlass: {enable: true, zoomFactor: 9.0},
   colorAxis: {colors: ['green', 'blue']}
 };

  var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
  chart.draw(data, options);
};
</script>
</head>
<body>
<h4>All cities with less than 10 startups have been exempted from this graph.</h4>
 <div id="chart_div" style="width: 900px; height: 500px;"></div>

Upon inspection, it's clear that I made the mistake of directly embedding Ruby into JavaScript, which surprisingly worked initially but now poses a challenge for serving this map effectively to users in production mode.

I am exploring different solutions:

  • Considering using the gon gem but unsure about its compatibility with the current complexity of the code.
  • Exploring the possibility of processing the data in JavaScript, although my knowledge in this area is limited, especially when dealing with an ActiveRecord call.
  • Tried disabling the JavaScript asset compiling in 'production.rb', but encountered difficulties. It's possible that I implemented it incorrectly.

Answer №1

To best utilize your Locations resource, consider exposing it as an API and then making an AJAX call to load it as JSON. This allows you to easily extract the data obtained from ActiveRecord by traversing the JSON object.

Modify your LocationsController as follows:

class LocationsController < ApplicationController
   respond_to :html, :json

   def index
      respond_with Location.all
   end

   ...
end

This configuration enables your Locations resource to respond to requests for data in either JSON or HTML formats. If accessing a list of Locations directly from the browser isn't necessary, omit :html from the respond_to method.

Utilize jQuery to retrieve Location data within your JavaScript code:

<script type='text/javascript'>
  google.load('visualization', '1', {'packages': ['geochart']});
  google.setOnLoadCallback(drawMarkersMap);

  function drawMarkersMap() {
    $.ajax({ url: '/locations', dataType: 'json' })
        .done(function(data) {
            // Format the retrieved JSON object according to your needs
        }
    );

     var options = {
      region: 'US',
      resolution: 'provinces',
      displayMode: 'markers',
      magnifyingGlass: {enable: true, zoomFactor: 9.0},
      colorAxis: {colors: ['green', 'blue']}
    };

     var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
     chart.draw(data, options);
};
</script>

The ajax call fetches your Location data in a JS-friendly JSON format. You'll need to further adjust this data to match Google Charts' requirements, but this serves as a solid foundation.

Unless there are additional complexities overlooked, leveraging Rails for such tasks is typically straightforward. It exemplifies one of Rails' strengths in handling scenarios like these.

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

How can I make the droppable elements only drop within draggable elements in jQuery UI?

After reading several similar articles and questions, I am still struggling to get this working properly when there are multiple droppable elements with the same named class. Is there a way to ensure that the dragged element can only be dropped in a speci ...

What is the best way to implement the useCallback hook in Svelte?

When utilizing the useCallback hook in React, my code block appears like this. However, I am now looking to use the same function in Svelte but want to incorporate it within a useCallback hook. Are there any alternatives for achieving this in Svelte? con ...

Ways to remove an item from firebase database

Currently, I am exploring ways to delete data stored in the Firebase database specifically under the requests category. Check out this example Below are the functions I have implemented to fetch and manipulate the data: export default { async contactArtis ...

Ways to update the select field without having to reload the entire page

I am working on a unique feature that involves two levels of drop down menus. When a user makes a selection in the first level, a corresponding set of options will appear in the second level. For example, I have 6 options in the first level, each with its ...

unable to access POST information

I have encountered an issue with getting a basic AJAX POST to function properly. After facing difficulties with using a jQuery .click, I switched to an onclick method. I am unsure if I am making a glaring mistake or if there could be an issue with Apache s ...

Exploring the potential of utilizing functions in express.js to take advantage of the "locals"

Having experience with Rails/Sinatra, I am accustomed to using helper functions in my view files. However, incorporating this functionality into express.js has proven to be quite challenging. You can include locals automatically like this... app.set("nam ...

The website functions properly in Chrome, but encounters issues in IE

Currently working on validating some JavaScript code. Chrome seems to be handling it well, but as expected, IE is causing some issues. Take a look at the code below: function validateData(a,id){ var inputs = document.getElementsByName('attname[] ...

Looking for assistance in transferring information from one webpage to another dynamic webpage

I'm in the process of building a website to feature products using NextJs. My goal is to transfer data from one page to another dynamic page. The data I am working with consists of a json array of objects stored in a data folder within the project. Wh ...

Utilizing Mantine dropzone in conjunction with React Hook Form within a Javascript environment

Can Mantine dropzone be used with React hook form in JavaScript? I am currently working on a modal Upload using Tailwind components like this import { useForm } from 'react-hook-form'; import { Group, Text, useMantineTheme } from '@mantine/c ...

Unable to activate Vue 13 keyCode in a text field using jQuery with Laravel Dusk Testing

I've been grappling with this issue for a few days now. I'm trying to create a Laravel Dusk test that incorporates the Vue.js framework. There's a method that should be triggered when the user hits the ENTER key. I recently discovered that ...

What causes the error when I use "use client" at the top of a component in Next.js?

Whenever I include "use client" at the top of my component, I encounter the following error: event - compiled client and server successfully in 2.5s (265 modules) wait - compiling... event - compiled client and server successfully in 932 ms (265 modules) ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Execute a multer request to upload an image (using javascript and express)

I am utilizing the Express server as an API gateway for my microservices, specifically to process and store images in a database. The issue at hand is that within the Express server, I need to forward an image received through a POST request from the clien ...

View a pink map on Openlayers 2 using an iPhone

I am currently working on a project where I am trying to track my location using my smartphone and display it on a map. To achieve this, I am utilizing openlayers 2. However, I am encountering an issue. When I implement the code below in a Chrome Browser ...

React Select only enabling single selection at a time

Currently, I am in the process of updating my react app to version 16.8 and also updating all associated libraries. One issue that has come up is with two drop-down selects from Material UI. Since the update, the multi-select option no longer allows multip ...

Using default language in Next.js internationalization: a step-by-step guide

I've been immersing myself in the Nextjs internationalization documentation for the past two days. My goal is to have support for two languages: en, fa. I also want to be able to switch between them with URLs structured like this: https://example.com ...

Looking to set up a web service that can handle incoming posts, but unsure about the best way to send a response back to jQuery

Good morning, I have a Go code that processes a JSON post request and performs certain actions. However, I am looking to send back either the result or a message to jQuery. package main import ( "fmt" "log" "net/http" "encoding/json" ...

Error: Authorization token is required

For email confirmation, I am utilizing JWT. An email is sent to the user with a URL containing the token. Here's an example of the URL received by the user: http://localhost:3000/firstlogin?acces_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI ...

Generate div elements dynamically for each object being populated in JSON using JavaScript

I have a main container that displays a list of JSON objects. Each object should be displayed as a separate DIV element with specific details, one after the other. Additionally, I have a comments section on a webpage where the details are stored in JSON f ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...