Ruby on Rails: How to Create a Statistics Panel in Administrate with Chartkick
When working with Administrate in your Rails application, you might find that you need a custom page to display important metrics or statistics, such as the number of customers or total sales. In this blog post, we’ll walk through how to add a custom statistics panel to your Administrate dashboard.
Step 1: Set Up the Administrate Controller for the Statistics Page
Administrate’s default behavior is to only show controllers that are tied to resources, but we can easily work around this by creating a controller for the statistics page without a related model. Official documentation
Create the following files:
1
2
3
4
5
6
# app/dashboards/stat_dashboard.rb
require "administrate/custom_dashboard"
class StatDashboard < Administrate::CustomDashboard
resource "Stats" # used by administrate in the views
end
1
2
3
4
5
6
7
8
9
10
11
# app/controllers/admin/stats_controller.rb
module Admin
class StatsController < Admin::ApplicationController
def index
@stats = {
customer_count: Customer.count,
order_count: Order.count,
}
end
end
end
1
2
3
4
5
# config/routes.rb
namespace :admin do
# ...
resources :stats, only: [:index]
end
And we can create a simple statistics page like this:
1
2
3
4
5
6
7
<div style="padding: 20px">
<h1>Stats</h1>
<br>
<p><b>Total Customers:</b> <%= @stats[:customer_count] %></p>
<br>
<p><b>Total Orders:</b> <%= @stats[:order_count] %></p>
</div>
Step 2: Adding Chartkick to display better looking charts
Setup Chartkick
Add this line to your application’s Gemfile and run bundle install:
1
gem "chartkick"
If you are using Importmap:
1
2
pin "chartkick", to: "chartkick.js"
pin "Chart.bundle", to: "Chart.bundle.js"
1
2
import "chartkick"
import "Chart.bundle"
You can find more information on the Official documentation
Use chartkick
Everything will work now if you try and use the gem in your pages, but because we want to display them in our administrate dashboard, things become a little bit tricky.
If we try and do the following
1
2
3
<div>
<%= line_chart User.group_by_day(:created_at).count %>
</div>
We will see “Loading…” instead of the chart being displayed.
We need to add the following line of code where we use Chartkick in administrate:
1
<%= javascript_include_tag 'chartkick', 'Chart.bundle' %>
To not copy paste it everywhere we can generate administrate’s layout by running this command:
1
bin/rails generate administrate:views:layout
After that we can add the line to application.html.erb so it is included everywhere.