RailsでHighchartJSを使ってみた

卒論のプログラムをレールに乗せよう計画の第1歩として,
HighChartJSを使えないかと模索したところ
Railsのgemで'lazy_high_charts'というのを発見!
サンプルを書いてみました.

Gemfileの中に'lazy_high_charts'を書いて
bundle installを行った後
適当にscaffold
ここらへんの環境がさくっと整うのがRailsですねー(´ω`)

controllerの中にこのように書いてあげて

class ChartsController < ApplicationController
  def index
    @charts = Chart.all
    score = []
    category = []
    @charts.each do |chart|
      score << chart.score
      category << chart.id
    end
    @graph = LazyHighCharts::HighChart.new('graph') do |f|
      f.title(text: 'Itemの在庫数')
      f.xAxis(categories: category)
      f.series(name:'在庫数', data:score)
    end
  end
end

viewのindex.html.erbにこれを追加すると

<%= high_chart('sample',@graph) %>

このようなグラフが作成出来ます.
f:id:pokotyamu:20140309234329p:plain
データに対応して,グラフが変化していくようなプログラムがさくさくっと書けました.

だがしかし,1つ気になったのが

class ChartsController < ApplicationController
  def index
    ids = Chart.select("id")
    scores = Chart.select("score")
    
    category = ids.each { |i|
      i.id
    }

    vals = scores.each { |s|
      s.score
    }

    @graph = LazyHighCharts::HighChart.new('graph') do |f|
      f.title(text: 'Itemの在庫数')
      f.xAxis(categories: category)
      f.series(name:'在庫数', data:vals)
    end
  end
end

これで返ってくるvals値が

[#<Chart id: 1, score: 900, created_at: "2014-03-08 16:21:38", updated_at: "2014-03-08 16:21:38">,
 #<Chart id: 2, score: 500, created_at: "2014-03-08 16:24:02", updated_at: "2014-03-08 16:24:02">]

こうなるのが,よく分からない.
まぁ,こっちの方が冗長になってる気もするからいいかなぁ(´・ω・`)

もっとオシャレなコードが書けるようになりたい...

参考:
Railsでグラフ表示 - わたしの脱コピペ駆動開発記