【Rails】lazy_high_chartsを用いてグラフを作成する方法


目標

本の月間登録推移を1日ごとに見れるグラフを作成します。

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

Slim導入
Bootstrap3導入
Font Awesome導入
ログイン機能実装
投稿機能実装

実装

1.Gemを導入

Gemfile
# 追記
gem 'lazy_high_charts'
ターミナル
$ bundle

2.application.jsを編集

application.js
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require highcharts/highcharts // 追記
//= require highcharts/highcharts-more // 追記
//= require_tree .

3.コントローラーを編集

books_controller.rb
def index
  @book = Book.new
  @books = Book.all
  # 追記
  days = (Date.today.beginning_of_month..Date.today).to_a
  books = days.map { |item| Book.where(created_at: item.beginning_of_day..item.end_of_day).count }
  @graph = LazyHighCharts::HighChart.new('graph') do |f|
    f.title(text: '本 月間登録推移')
    f.xAxis(categories: days)
    f.series(name: '登録数', data: books)
  end
end

① 今月1日から今日までの日付を取得し、変数へ代入する。

days = (Date.today.beginning_of_month..Date.today).to_a

で取得した日付内に作成された本の数を取得し、変数へ代入する。

books = days.map { |item| Book.where(created_at: item.beginning_of_day..item.end_of_day).count }

③ グラフを作成する

@graph = LazyHighCharts::HighChart.new('graph') do |f|
  f.title(text: '本 月間登録推移') # タイトル
  f.xAxis(categories: days) # 横軸
  f.series(name: '登録数', data: books) # 縦軸
end

4.ビューを編集

books/index.html.slim
/ 追記
= high_chart('sample', @graph)