1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Posted at

目標

本の月間登録推移を1日ごとに見れるグラフを作成します。
ezgif.com-video-to-gif.gif

開発環境

・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)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?