繁体   English   中英

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

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

我想在Rails应用程序(减肥应用程序)中使用Chart.js在“体重”索引页面上显示折线图。 我有一个表格,其中包含每天(作为“天”)的用户体重(作为“千克”)。 但是,我只能显示折线图,而只能显示静态数据,而不能显示“重量”表中的数据。

我现在想做的是在x轴上有“天”,在y轴上有“千克”。

我该如何实现? 正如我几个月前才开始编写代码一样:代码应该是什么样?

多谢。

这是我的体重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>

让我永远困扰的主要事情是Chart.js依赖于使用<%调用其工具提示模板,但是ERB会对此加以解释并引起问题。 解决方法是添加另一个% ,该%告诉erb不要解释它原本应具有的标签。 记录的不是很好,但是您将要做什么。 至于其余的内容,您想在view-page.html.erb文件的底部添加图表脚本:

设置您的时间轴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 %>,
            }]
    };

如果要设置一些选项,请记住使用<%%标签作为工具提示!

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>

我也很努力地使它在Rails上起作用,但是我发现我不必使用chart.js所说的可以使用的Rails模板转义字符。 在我的情况下(将值设置为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-2025 STACKOOM.COM