Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
Ruby on Rails: preferred method of calling data into javascript?

Use case: I have a static view displaying data from the controller (application record data). I only need to get this data once, and it has to be passed into the view's javascript (I am using a pivottable js library).

Which is better for calling data from our controller into our view's javascript?

Option 1:

  var data = JSON.parse('<%= @result %>');

Option 2:

$.ajax({
       url: "<%= path_to_data %>",
       type: "GET",
       dataType: "json",
       data: JSON.stringify(table),    
 });

What are the pros and cons of the options? One problem is that with option 1, rails writes @result into the javascript which, with large data, looks time consuming to write into the script (as well as visually unappealing when looking at the rendered javascript). Option 2, however, requires an additional GET call to our controller.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Option 3.

Don't use erb interpolation in your JS at all - use data attributes to pass information from the view.

<div id="graph-module" data-source-url="<%= path_to_data %>">
  ...
</div>
let promise = $.getJSON($('#graph-module').data("url"));

promise.done(function(data){
  // do something with the data
});

Yes this will create an additional GET request but its well worth it in my books to avoid muddling together the server side and client side domains into mush which is something Rails does far too eagerly.

This keeps your JS in the assets pipeline (or webpacker) where it can be minified, cached and deployed via a CDN instead of a JS/ERB soup that changes depending on the current request.

Its also just easier to debug, reason about and in general write good code when its in a seperate file and does not rely on being parsed through another langauge. It allows you to use linting tools like JSLint.

If you want to use option 1 in a meaningful way you need to use a global instead of var.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!