Question

I have a rails application which is serving up a number of views which include specific data from the database to be manipulated by some javascript, specifically for use with Chartjs.

Options I have explored are:

  1. Use an ajax call to pull the data off the server. I don't like this one because the user isn't changing any data, I have access to all the data when I render the page, there ought to be a better way.
  2. Use <script> tags in the view ERB and simply have ERB interpolate the variable. This seems a little hacky and definitely doesn't take advantage of all my beautiful haml. But it is easy and allows me to put javascript variables on the page which can then be picked up after the document.onload.
  3. Gon. Great gem and very easy. But should this really require a gem?

I feel as though the solution should involve the asset pipeline and some sort of rails interpolation, but I can't seem to make that work very cleanly. What is the elegant rails 4 way for solving this?

Thanks everyone!

Was it helpful?

Solution

There are many ways to pass data from server-side to javascript, I'll list two of the most common (that don't use a gem or other external tools) below:

  1. Use the second method you described, and interpolate ERB tags inside the javsacript. This is ugly, hacky and is not even close to best practice.

  2. Use data attributes. You can modify your HAML to include additional attributes, like "data-my-variable", and access it via javascript (example using jQuery: $(element).data("my-variable")).

The data attribute method is, in my opinion, the cleanest way of doing this, it's exactly the purpose of data attributes.

Now, I don't know HAML, I've only worked with ERB before, but I found this answer by Mandeep, which explains how you can add data attributes to your HAML:

%a{"data-my-variable" => "my data", href: "#"}

OR

%a{href: "#", :data => {:my_variable => "my data"}}

EDIT: Sorry, I found your question along with other, newer, questions, I just assumed it was recent, and not from over a year ago :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top