2016-07-27 202 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