Now a days in many website we use chart to show the statistics for the site and there are many plugins and gems available for it. But I liked one gem Chartkick that I used in one of our application to create column chart to show weekly, yearly and From date - ToDate range statistics of site. I found it very useful and easy to use. You will get details about chartkick here.
Let’s begin with Installation: In gem file, add:
In application.js, add:
//= require chartkick
Note: In the instructions below, application.js must be included before the helper methods in your views, unless using the :content_for option.
In your views, before application.js, add:
Now, You are ready to create chart. Only add one line of ruby code to generate chart of any type for example pie chart, line chart, area chart, column chart and many more. For example.
<%= column_chart Order.group_by_week(:created_at, format: "%a").count %>
In the above example, I have just shown you how we can make a column chart. Similarly you can create other charts.
group_by_week is the method from Groupdate. You need to install Group date gem to use this method. Using groupdate you can group by:
You will get more information about Groupdate here.
Now, let’s have some real fun by using Chartkick to create some interactive Graphs, using Dynamic data.
To create a graph which drives data from the ajax request, you just need to define a method in the controller and pass the JSON data. For example
class ViewsController < ApplicationController def show @view = View.all end def views_by_day render json: View.group_by_day(:viewed_at, format: "%a").count end
Next, add in the code listed below to your views/show view. app/views/views/show.html.haml:
.container .h3 Views By Day = column_chart views_by_day_view_path
There you have it how you want.