4

私はRoR/Rubyにまったく慣れておらず、Lazy High Charts gemを使用して、データベース情報に基づいていくつかのpurdyチャートを生成しています。

私は前の質問で提供された答えを試しましたが、これを行う方法についてはまだ少し混乱しています。

amount_used、billed_amountを合計し、月/年ごとにグループ化する必要があります(例:2012年8月)

最終結果は、「使用量」と「コスト」の2つのシリーズを持つ2軸グラフに似たものになります。この情報は、特定のaccount_idに固有です。

ここに画像の説明を入力してください

請求書テーブル

+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| account_id    | int(11)      | YES  |     | NULL    |                |
| invoice_date  | varchar(255) | YES  |     | NULL    |                |
| amount_used   | float        | YES  |     | NULL    |                |
| billed_amount | float        | YES  |     | NULL    |                |
| comments      | text         | YES  |     | NULL    |                |
| created_at    | datetime     | NO   |     | NULL    |                |
| updated_at    | datetime     | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+

コントローラチャートコード

@account = Account.find(params[:id])
@invoices = Invoice.where("account_id = #{@account.id}").order("invoice_date DESC")

@h = LazyHighCharts::HighChart.new('area') do |f|
  f.options[:chart][:defaultSeriesType] = "area"
  #Sample dates right now, should be the grouped_by :invoice_date
  f.xAxis( :categories => ['May', 'Jun', 'Jul'] )
  f.yAxis([
    {
      :title => { :text => "Amount Used" }
    },
    {
      :title => { :text => "Cost" },
      :opposite => true
    }
  ])
  #Sample data right now, should be the summed amounts of the :amount_used correpsonding for each above grouped invoice_date
  f.series(:name => "Amount Used", :data => [100,300,500] )
  #Sample data right now, should be the summed amounts of the :billed_amount correpsonding for each above grouped invoice date
  f.series(:name => "Cost", :yAxis => 1, :data => [200,400,600] )
end 
4

1 に答える 1

13

すべて揃っているようです。db からデータを取得する方法は次のとおりです。

@aggregated_invoices = Invoice.
  where(:account_id => params[:id]).
  order("invoice_date DESC").
  group("invoice_date").
  select("DATE_FORMAT(invoice_date, '%Y-%m-01') AS invoice_date, sum(amount_used) AS amount_used, sum(billed_amount) AS billed_amount")

# Then use these instead of sample data:
@categories = @aggregated_invoices.map {|i| i.invoice_date.strftime("%b/%Y")}
@amount_used_data = @aggregated_invoices.map(&:amount_used)
@billed_amount_data = @aggregated_invoices.map(&:billed_amount)
于 2012-09-11T14:20:44.100 に答える