I used chart kick because I wanted to insert a graph in rails. Since the introduction itself is easy, we will describe how to make a pie chart of the aggregated results.
ruby 2.5.1 Rails 184.108.40.206
Create a pie chart from the ** opinion column (integer) ** of the ** votes table ** that summarizes the user's opinions. If the value of the opinion column is 1, it is for, and if it is 0, it is the opposite, but it is created with other values and NULL values mixed.
** votes table **
** Rendering **
Although it is described on the reference page, it will be described again.
gem "chartkick" #Append
$ bundle install
//= require chartkick //= require Chart.bundle #Add two lines
The page to be displayed can be anywhere, but this time I would like to display the graph in index.html.erb of the posts controller.
<%= pie_chart Vote.group(:opinion).count%>
It's a graph that you don't really understand what it represents. ..
Therefore, define variables and methods for graphs in the controller file.
def index @opinion = Vote.pluck(:opinion) @aggregate = aggregateOpinion(@opinion) @sum = sumOpinion(@opinion) end def aggregateOpinion(array) result = [["Agree",0],["Opposition",0],["Neither",0],["No answer",0]] array.each do |i| if i == 1 result += 1 elsif i == 0 result += 1 elsif i == nil result += 1 else result += 1 end end return result end def sumOpinion(array) result = [["Total votes",0],["Number of valid votes",0],["Number of invalid votes",0]] array.each do |i| if i == nil result += 1 else result += 1 end end result = array.length return result end
Only the target column is fetched as an array with the pluck method. After that, the aggregateOpinion method is used to format the data for a pie chart.
Since the index of the result array is the display order of the pie chart as it is, the parameter is The null value comes last, followed by the so-called "other" (in this case, the name [neither]).
The sumOpinion method is not directly related to the graph, but it is difficult to put the information on the total number of votes on the graph, so it is created separately.
Based on the above contents, I would like to reflect it on the view page again.
<%= pie_chart @aggregate, width: "500px"%>
This is no problem, but at the end, the layout and the contents acquired by the sumOpinion method are displayed in the table element, and it is completed.
<%= pie_chart @aggregate,colors: ["#3333cc","#cc3333","#339966","333"], donut: true , width: "500px"%> <table border="1" width="500"> <tr> <th>Total votes</th> <th>Number of valid votes</th> <th>Number of invalid votes</th> </tr> <tr> <th><%[email protected]%></th> <th><%[email protected]%></th> <th><%[email protected]%></th> </tr> </table>
What did you think. I think I was able to apply it to the method part a little more. .. Of course, chartkick does not only support pie charts, so please check it out. Thank you for watching!