I'm trying to render the basic line chart using Chartkick (with the default, Chart.js) in Ruby on Rails. I have followed the installation instructions here () and added:
gem "chartkick"
to the gem filepin "chartkick", to: "chartkick.js"
and pin "Chart.bundle", to: "Chart.bundle.js"
to importmap.rb<%= javascript_importmap_tags %>
<%= line_chart User.group_by_day(:created_at).count %>
. I have tried a more basic, <%= line_chart({"2021-01-01" => 2, "2021-01-02" => 3}) %>
.This render a page that says, "Loading...". An inspection of that page shows,
(function() {
if (document.documentElement.hasAttribute("data-turbolinks-preview")) return;
if (document.documentElement.hasAttribute("data-turbo-preview")) return;
var createChart = function() { new Chartkick["LineChart"]("chart-2", [["2021-01-01",2],["2021-01-02",3]], {}); };
if ("Chartkick" in window) {
createChart();
} else {
window.addEventListener("chartkick:load", createChart, true);
}
})();
Can someone please let me determine what steps I'm missing to show the graph?
I'm trying to render the basic line chart using Chartkick (with the default, Chart.js) in Ruby on Rails. I have followed the installation instructions here (https://chartkick./#installation) and added:
gem "chartkick"
to the gem filepin "chartkick", to: "chartkick.js"
and pin "Chart.bundle", to: "Chart.bundle.js"
to importmap.rb<%= javascript_importmap_tags %>
<%= line_chart User.group_by_day(:created_at).count %>
. I have tried a more basic, <%= line_chart({"2021-01-01" => 2, "2021-01-02" => 3}) %>
.This render a page that says, "Loading...". An inspection of that page shows,
(function() {
if (document.documentElement.hasAttribute("data-turbolinks-preview")) return;
if (document.documentElement.hasAttribute("data-turbo-preview")) return;
var createChart = function() { new Chartkick["LineChart"]("chart-2", [["2021-01-01",2],["2021-01-02",3]], {}); };
if ("Chartkick" in window) {
createChart();
} else {
window.addEventListener("chartkick:load", createChart, true);
}
})();
Can someone please let me determine what steps I'm missing to show the graph?
To solve this issue, you need to put <%= javascript_include_tag "//www.google./jsapi", "chartkick" %>
in application.html.erb.
For me, the issue was being caused by "defer: true" in the application.js import:
<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>
Removing defer solved it for me (AND making sure include_tag is in head, not right before /body). Charts began working again:
<%= javascript_include_tag "application", "data-turbo-track": "reload" %>
I can only assume that Chartkick doesn't like to load too late. I tried creating a new file next to application.js with only import "chartkick/chart.js"
and its own include_tag without defer, but errors were thrown in the browser console.
Would love a way to use defer and have Chartkick work, but I couldn't find one. Let me know if anyone has found a solution.