简体   繁体   English

在Chart.js / Rails中使用数据库中的数据

[英]Use data from database in Chart.js/Rails

I want to show a line chart on my "Weights" index page with Chart.js in my Rails app (a weight loss app). 我想在Rails应用程序(减肥应用程序)中使用Chart.js在“体重”索引页面上显示折线图。 I have a table that holds a user's weight (as "kilograms") for each day (as "day"). 我有一个表格,其中包含每天(作为“天”)的用户体重(作为“千克”)。 I am able to show a line chart, however, but only with static data - not with the data from my Weights table. 但是,我只能显示折线图,而只能显示静态数据,而不能显示“重量”表中的数据。

What I want to do now is to have "day" on the x-axis and "kilograms" on the y-axis. 我现在想做的是在x轴上有“天”,在y轴上有“千克”。

How can I achieve this? 我该如何实现? And as I just started coding few months ago: how should the code look like? 正如我几个月前才开始编写代码一样:代码应该是什么样?

Thx a lot. 多谢。

This is the code from my weights index.html.erb: 这是我的体重index.html.erb中的代码:

<canvas id="myChart" width="400" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["day 1", "day 2", "day 3", "day 4", "day 5", "day 6"],
        datasets: [{
            label: 'My Weight',
            data: [82.4, 79.6, 79.3, 78.4, 77.5, 75.1],
            backgroundColor: [
                'rgba(0, 0, 0, 0.1)',
            ],
            borderColor: [
                'rgba(0,0,0,0.9)',
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:false
                }
            }]
        }
    }
});
</script>

The main thing that had me stuck forever was that Chart.js relies on calling its tooltiptemplate with <% however this would then be interpreted by ERB and cause a problem. 让我永远困扰的主要事情是Chart.js依赖于使用<%调用其工具提示模板,但是ERB会对此加以解释并引起问题。 The workaround is adding another % which tells erb not to interpret the tags it otherwise would have. 解决方法是添加另一个% ,该%告诉erb不要解释它原本应具有的标签。 That's not very well documented but what are you going to do. 记录的不是很好,但是您将要做什么。 As for the rest, in your view-page.html.erb file you want to add the chart scripts at the bottom: 至于其余的内容,您想在view-page.html.erb文件的底部添加图表脚本:

Set your timeline X-Axis (I'll show you how to load it dynamically but this could be static if you want in which case just enter them directly into the timeline array): 设置您的时间轴X轴(我将向您展示如何动态加载它,但如果您想在这种情况下将其直接输入到时间轴数组中,则可以是静态的):

<script type="text/javascript">
$(function() {
      var lineData = {
      <% timeline = []
         datapoints = []
        @workout.each do |workout|
          timeline << workout.day
          datapoints << workout.weight
       end
 %>
       //The "raw" method is needed to stop the auto escaping of the output.  Test this out in your console and you will notice the output is formatted like "[\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\"]"  This escaping of quotes causes errors in js...
      labels: <%= raw timeline.to_json %>,
        datasets: [{
                label: "Weight Gain/Loss",
                fillColor: "rgba(26,179,148,0.5)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#127A65",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: <%= raw datapoints.to_json %>,
            }]
    };

If you want to set some options remember to use the <%% tag for tooltips! 如果要设置一些选项,请记住使用<%%标签作为工具提示!

var lineOptions = {
            scaleOverride : true,
            tooltipTemplate: "<%%if (label){%>(<%%=label%>) <%%}%><%%= value %>  pounds",
    };
    //NOTE THE ABOVE TOOLTIP REQUIRES A SECOND % SIGN ON OPENING TAGS SO THAT IS IS TAKEN LITERALLY AND NOT INTERPRETED BY RAILS ERB!!!!!!!!

var ctx = document.getElementById("myChart").getContext("2d");

var myNewChart = new Chart(ctx).Line(lineData, lineOptions);

});
</script>

I, too, was struggling with getting this to work on Rails, but I discovered that I did not have to use the Rails template escape characters that chart.js says that you do. 我也很努力地使它在Rails上起作用,但是我发现我不必使用chart.js所说的可以使用的Rails模板转义字符。 In my case (needing to show a zero in the label when the value is set to 0.1), this is what I did: 在我的情况下(将值设置为0.1时需要在标签中显示零),这就是我所做的:

tooltipTemplate: function(context){
  var labelVal = (context.value == '0.1')? '0' : context.value;
  var newLabel = context.label + ': ' + labelVal;
  return newLabel;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM