2016-07-27 206 views
0

我想为我的公司的实习项目创建一个线图。在yAxis我想要订单。在xAxis我想要月份(1月至12月)。所以xAxis上有12个标签。我的问题是,只有前12个订单从数据中挑选出来:我怎样才能解决这个问题 ?同样的问题是一个月。我在这里放了一个链接来说明。 http://imgur.com/a/VJBvj 这里是我的代码:Chart.js数据/标签刻度

<canvas id="orderChartCurrentMonth" width="400" height="400"></canvas> 
<script> 
    <%= foo = ((Date.today).beginning_of_month) %> 
    var ctx = document.getElementById("orderChartCurrentMonth"); 
    var orderChartCurrentMonth = new Chart(ctx, { 
    type: 'line', 
    data: { 
     labels: [ 
     "<%=foo %>", "<%=foo + 1.week%>", "<%=foo + 2.week %>","<%=foo + 3.week%>", "<%=foo + 4.week%>" 
     ], //x-Achse 
     datasets: [{ 
     label: 'Graph Orders last week', 
     data: <%= (foo..foo.end_of_month).map { |date| Company.graph_order(date).to_f}.inspect %> //y-Achse 
     }]}, 
    options:{ 
     legend:{ 
     display: false 
     }, 
     scales: { 
     xAxes: [{ 
      ticks: { 
      stepSize: 10 
     }}]}}}) 
</script> 

问候

回答

0

您应该使用提供按月(或周)分组集合数据的查询。虽然你可以使用数据库的日期函数来完成,但我建议使用Groupdate gem,以便在需要频繁使用时简化流程。你可以做类似的事情。

# this should probably be done in a controller action 
<% @data = Order.where(date: 1.years.ago.beginning_of_month..Time.now).group_by_month(:date).count %> 


# get an array of monthly labels in js file 
... 
labels: <%= @data.map{ |month, order_count| month } %> 
... 

# get the values for those months 
... 
data: <%= @data.map{ |month, order_count| order_count } %> 
... 

不用说,这个例子只是显示每月订单数。如果您需要其他值,则必须调整查询。此外,Groupdate提供了很多选项来分组这些数据。请务必阅读文档:https://github.com/ankane/groupdate