[Ruby on Rails] Implement a pie chart that specifies the percentage of colors

I personally create something like a "closet app" that allows me to manage my own clothes, because I want it and it will be interesting to make it. Therefore, I thought it would be great if I could display the color ratio of my clothes in a pie chart in an easy-to-understand manner, so I implemented it this time.

Development environment

Ruby 2.5.1p57 Rails 5.2.4.4 Use gem ・ Active_hash ・ Chartkick ・ Chartable

I will actually make it

I was very worried about where to store the actual color data this time, but I decided to use active_hash, have the model have the data in hash format, and store the ID in a database called "colors".

First, write the following in the Gemfile.

Gemfile


#~abridgement~
gem 'active_hash'
gem "chartkick"
gem 'chartable'
#~abridgement~

Describe the following in application.js.

application.js


//= require Chart.bundle
//= require chartkick

And here is a model with actual color data using Active_hash.

color_data.rb


class ColorData < ActiveHash::Base
  self.data = [
    { id: 1, name: 'white', backcolor: "#fff" },
    { id: 2, name: 'black', backcolor: "#000" },
    { id: 3, name: 'gray', backcolor: "#808080" },
    { id: 4, name: 'Brown', backcolor: "#660000" },
    { id: 5, name: 'beige', backcolor: "#FFE4C4" },
    { id: 6, name: 'green', backcolor: "#006400" },
    { id: 7, name: 'blue', backcolor: "#0000CD" },
    { id: 8, name: 'purple', backcolor: "#8B008B" },
    { id: 9, name: 'yellow', backcolor: "#FFFF00" },
    { id: 10, name: 'pink', backcolor: "#FF82B2" },
    { id: 11, name: 'Red', backcolor: "#FF0000" },
    { id: 12, name: 'Silver', backcolor: "#C0C0C0" },
    { id: 13, name: 'gold', backcolor: "#DAA520" }
  ]
end

I wrote it like this. The key "backcolor" is the data to pass the specified color to each item of the pie chart.

And model. I wanted to pass the graph data to the controller in hash format and the background color data as an array, so it's a lot of help and it's a redundant code that repeats the same thing ... I'm looking for a better way here.

color.rb


class Color < ApplicationRecord
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :color_data
  class << self
    #Methods that form the hash data to pass to the graph
    def color_data_acquisition_for_graphs
      colors = all
      color_graph_data = {}
      colors.each_with_index do |color, index|
        color_graph_data = { color.color_data.name => 1 } if index.zero?
        #Turn the data acquired from DB in each and check if it already exists as a key
        #If it already exists, add 1 to the value that is the standard of the ratio.
        if color_graph_data.key?(color.color_data.name)
          color_graph_data[color.color_data.name] += 1
        else
          color_graph_data[color.color_data.name] = 1
        end
      end
      color_graph_data
    end

    def background_color_data_acquisition_for_graphs
      colors = all
      color_graph_data = {}
      background_colors = []
      colors.each_with_index do |color, index|
        if index.zero?
          color_graph_data = { color.color_data.name => 1 }
          #Add background color data (backcolor data)
          background_colors << color.color_data.backcolor
        end
        if color_graph_data.key?(color.color_data.name)
          color_graph_data[color.color_data.name] += 1
        else
          color_graph_data[color.color_data.name] = 1
          #The order is kept to add backcolor when a key that has not been imported yet comes
          background_colors << color.color_data.backcolor
        end
      end
      background_colors
    end
  end
end

Please do not refer to this here lol (someone if there is a good way to write ...)

Then pass the data created here to the controller.

closet_controller.rb


class ClosetController < ApplicationController
  def index
    @color_graph_data = Color.color_data_acquisition_for_graphs
    @background_colors = Color.background_color_data_acquisition_for_graphs
  end
end

Then pass the aggregated data for the graph and the data for coloring the graph to the view.

All you have to do is display it.

ruby:index.html.slim


= pie_chart @color_graph_data, colors: @background_colors

With this alone ...

スクリーンショット 2020-10-11 14.34.47.png

It can be displayed like this.

By the way, if you don't need the menu items, you can hide it by creating a file called "chartkick.rb" under config / initializers / and writing options.

chartkick.rb


Chartkick.options = {
  legend: false
}

By doing this,,,

スクリーンショット 2020-10-11 14.39.00.png

At first, I wondered if I had to conditionally branch the color specified for the background depending on the color, but at the time of Active_hash in the first place, I came up with the idea of having each background color value. It was good.

It will be a development with 28 tables, which is the largest number in history for personal apps, so I will do my best while having fun.

Recommended Posts

[Ruby on Rails] Implement a pie chart that specifies the percentage of colors
(Ruby on Rails6) Display of the database that got the id of the database
A note about the seed function of Ruby on Rails
part of the syntax of ruby ​​on rails
[Ruby on Rails] Create a pie chart for each column with Chartkick
[Ruby on Rails] Until the introduction of RSpec
[Ruby on Rails] A memorandum of layout templates
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
Docker the development environment of Ruby on Rails project
Try using the query attribute of Ruby on Rails
[Ruby on Rails] Implementation of validation that works only when the conditions are met
Determine that the value is a multiple of 〇 in Ruby
Delete all the contents of the list page [Ruby on Rails]
Explanation of Ruby on rails for beginners ③ ~ Creating a database ~
Basic knowledge of Ruby on Rails
[Ruby on Rails] Change the save destination of gem refile * Note
(Ruby on Rails6) Create a function to edit the posted content
Create a large number of records with one command using the Ruby on Rails seeds.rb file
[Ruby on Rails] Introduction of initial data
Let's summarize "MVC" of Ruby on Rails
[Ruby on Rails] Japanese notation of errors
How to solve the local environment construction of Ruby on Rails (MAC)!
Explanation of Ruby on rails for beginners ①
[Ruby on rails] Implementation of like function
Ruby on Rails When you don't know the cause of rollback when saving.
A series of flow of table creation → record creation, deletion → table deletion in Ruby on Rails
[Ruby On Rails] How to search the contents of params using include?
[Ruby on Rails] How to make the link destination part of the specified id
How to resolve errors that occur in the "Ruby on Rails" integration test
[Ruby on Rails] Try to create a service that makes local cats happy
[Ruby on Rails] How to Japaneseize the error message of Form object (ActiveModel)
Implementation of Ruby on Rails login function (Session)
When the Ruby on Rails terminal rolls back
Recommendation of Service class in Ruby on Rails
Publish the app made with ruby on rails
Ruby on Rails ~ Basics of MVC and Router ~
(Ruby on Rails6) Creating data in a table
Determine the current page with Ruby on Rails
[Ruby on Rails] Individual display of error messages
I made a portfolio with Ruby On Rails
[Ruby] I want to make a program that displays today's day of the week!
[Ruby On Rails] Description that allows only specific users to transition to the edit page
[Rails] Implement a counter that counts the parent category when registering a child category (ancestry, counter_culture)
[Ruby On Rails] Correct description location of unique constraint that gives uniqueness to DB
A review of the code used by rails beginners
Ruby on Rails <2021> Implementation of simple login function (form_with)
Count the number of occurrences of a string in Ruby
[Ruby on Rails] Asynchronous communication of posting function, ajax
[Introduction] Try to create a Ruby on Rails application
[Ruby on Rails Tutorial] Error in the test in Chapter 3
Build a Ruby on Rails development environment on AWS Cloud9
Implementation of Ruby on Rails login function (devise edition)
[Ruby on Rails] How to change the column name
[Ruby / Rails] Set a unique (unique) value in the class
[Rails] Volume that displays favorites and a list of favorites
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on
Explanation of Ruby on rails for beginners ⑥ ~ Creation of validation ~
Explanation of Ruby on rails for beginners ② ~ Creating links ~
(Ruby on Rails6) Reflecting the posted content from the form
Explanation of Ruby on rails for beginners ⑦ ~ Flash implementation ~
Ruby on Rails 5 quick learning practice guide that can be used in the field Summary