[Ruby] [Rails] How to create a graph using lazy_high_charts

1 minute read

Target

** Create a graph that shows the monthly registration transition of books on a daily basis. ** **
ezgif.com-video-to-gif.gif

Development environment

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

Premise

The following has been implemented.

Slim introduction
Introduction of Bootstrap3
Introduction of Font Awesome
-Login function implementation
Implementation of posting function

Implementation

1. Introduce Gem

Gemfile


#Postscript
gem 'lazy_high_charts'

Terminal


$ bundle

2. Edit ʻapplication.js`

application.js


//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require highcharts/highcharts //Postscript
//= require highcharts/highcharts-more //Postscript
//= require_tree .

3. Edit controller

books_controller.rb


def index
  @book = Book.new
  @books = Book.all
  #Postscript
  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: 'Monthly registration transition')
    f.xAxis(categories: days)
    f.series(name: 'Registration number', data: books)
  end
end

(1) Get the date from the 1st of this month to today and assign it to the variable.

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

(2) Acquire the number of books created within the date acquired in and assign them to variables.

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

③ Create a graph

@graph = LazyHighCharts::HighChart.new('graph') do |f|
  f.title(text: 'Monthly registration transition') #title
  f.xAxis(categories: days) #Horizontal axis
  f.series(name: 'Registration number', data: books) #Vertical axis
end

4. Edit the view

slim:books/index.html.slim


/Postscript
= high_chart('sample', @graph)