Dashboards
dashboard adds a dashboard page to a model, built from rows of metric cards, charts and tables. Each widget gets its data from a helper method or block that receives permission-scoped records and the applied filters.
Quick exampleβ
catalyst do
dashboard :user_dashboard, display_name: "User Dashboard" do
filter :ct_role_id, :single_select, helper_method: :select_options_for_ct_role
row do
section "" do
metric_card :total_users_metric, title: "Total Users"
end
section "" do
chart :users_by_role_chart_data, title: "Users by Role", chart_type: :pie
end
end
end
end
module Catalyst
module DashboardHelper
def total_users_metric(scoped_ar_object, _scoped_filters = {})
scoped_ar_object.count
end
def users_by_role_chart_data(scoped_ar_object, _scoped_filters = {})
scoped_ar_object.joins(:ct_role).group("ct_roles.name").count
end
end
end
The dashboard is served at /admin/<models>/<name> (here /admin/users/user_dashboard). Enable its permission for each role in Roles β Permissions.
Optionsβ
dashboard(name, display_name: nil, icon_name: nil, page_title: nil, page_description: nil, partial: nil)
| Name | Type | Default | Description |
|---|---|---|---|
name | Symbol | required | Unique action name of the dashboard. Define several with different names. |
display_name | String | nil | Label of the dashboard link. |
icon_name | String | nil | Icon of the dashboard link. |
page_title | String | display_name, or "<Models> Dashboard" | Page title. |
page_description | String | nil | Text below the title. |
partial | String | nil | Render this partial instead. |
Inside the block, use filter, sort, row and section, and these widgets inside sections:
| Widget | Signature | Options |
|---|---|---|
metric_card | metric_card(helper_method, options = {}) | title, description, col_size (default 6), align, display_if, html_attrs, partial. Can also take a block β see Metric Cards |
chart | chart(helper_method, options = {}) | title, description, chart_type (default :line), x_label, y_label, unit, decimals, colors, highlight, animation, date_format, col_size (default 12), chart_attrs, display_if, html_attrs β see Charts |
table | table(source_method, options = {}) { ... } | title, description, associated_model_name, per_page (default 20), eager_load_associations, display_if. Declare column and sort inside the block β see Tables |
Helper methods live in Catalyst::DashboardHelper and receive (scoped_ar_object, scoped_filters).
Widget Typesβ
Metric Cardsβ
Display single numeric values:
metric_card :total_users_metric, title: "Total Users", description: "All registered users"
A metric card can also show how the number has moved. Return a hash with the previous value and the card adds a green or red badge with the percentage change and a "vs." line:
metric_card "New users" do |scope|
{
value: scope.where(created_at: Time.current.all_month).count,
previous: scope.where(created_at: 1.month.ago.all_month).count,
period: "last month" # optional, "last period" by default
}
end
Return {value:, change: 4.2} instead to state the percentage yourself.
align: sets the alignment of everything in the card: :left (the default), :center or :right.
metric_card "Total users", align: :center do |scope|
scope.count
end
Numbers are shown with thousands separators.
Chartsβ
Charts are drawn with Apache ECharts. Catalyst builds the ECharts option on the server and a Stimulus controller draws it, so ECharts is only downloaded on pages that show a chart.
chart :users_by_role_chart_data, chart_type: :pie, title: "Users by Role"
chart :daily_signups_chart_data, chart_type: :line, title: "Daily Signups"
chart :monthly_stats_chart_data, chart_type: :bar, title: "Monthly Stats"
chart :signups_by_role, chart_type: :stacked_bar, title: "Signups by Role"
chart_type | Draws |
|---|---|
:line | Line chart (the default) |
:area | Line chart with the area under the line filled |
:stacked_area | Filled lines stacked on top of each other |
:bar | Bar chart with value labels |
:horizontal_bar | Bars running left to right, categories on the y axis |
:stacked_bar | Bars stacked per category, one per series |
:stacked_horizontal_bar | Stacked bars running left to right |
:pie | Pie chart with name: value (percent) labels |
:donut | Pie chart with a hole in the middle |
:gauge | Dial showing one value in a range |
:grade_gauge | Half-circle gauge with coloured grade bands |
:progress_gauge | Ring that fills up to the value |
:custom | Any ECharts option, returned by the data method |
The older names with a _chart suffix (:pie_chart, :stacked_bar_chart, β¦) still work.
Where the data comes fromβ
A chart or metric card gets its data from a block or a method. Both work on dashboards and on show pages.
A block. Return the query result as it is:
chart "Requests by status", chart_type: :pie do |scope|
scope.group(:status).count
end
chart "Signups by role", chart_type: :stacked_bar, date_format: "%b %Y" do |scope|
scope.joins(:ct_role).group("ct_roles.name").group_by_month(:created_at).count
end
metric_card "Total requests" do |scope|
scope.count
end
A method. Pass its name as a symbol, as in the examples above. Use this when the query is long or shared.
A block or method on a dashboard is offered the permitted records and then the active filters. It receives as many as it accepts, so |scope|, |scope, filters| and no arguments all work. On a show page a block receives the record, and a method is called on the record with no arguments.
Data shapesβ
The data method returns one of these:
# One series: a hash, or an array of pairs
{"Jan" => 3, "Feb" => 5}
[["Jan", 3], ["Feb", 5]]
# Several series: one entry per series
[
{name: "Admin", data: {"Jan" => 2, "Feb" => 1}},
{name: "Staff", data: {"Jan" => 4, "Mar" => 6}}
]
# Several series, straight from a two-column group: the first key is the series
{["Admin", "Jan"] => 2, ["Staff", "Jan"] => 4} # User.group(:role).group_by_month(:created_at).count
Series are aligned by category, so they do not need the same keys: a category a series lacks is left empty. Labels are tidied for you: dates are formatted (date_format: "%b %Y" to change how), a nil key becomes "Other", and snake_case keys such as enum values are humanised. Returning a String shows it as a warning instead of a chart, and empty data shows "No data available".
Stacked bar chartsβ
A stacked bar chart needs the multi-series shape. With groupdate, grouping by two columns gives [series, category] keys that convert directly:
def self.signups_by_role(scope, _filters = {})
counts = scope.joins(:ct_role).group("ct_roles.name").group_by_month(:created_at, format: "%B %Y").count
counts.group_by { |(role, _month), _count| role }.map do |role, rows|
{name: role, data: rows.to_h { |(_role, month), count| [month, count] }}
end
end
chart :signups_by_role, chart_type: :stacked_bar, title: "Signups by Role"
Gauge chartsβ
A :gauge is a dial showing one value: a number, or a one-entry hash to name it. The range defaults to 0 to 100.
chart :queue_load, chart_type: :gauge, chart_attrs: {max: 200} # {"Load" => 40}
Custom chartsβ
For anything else ECharts can draw (treemap, heatmap, sankey, candlestick, β¦), use :custom. The data method returns a complete ECharts option, which is drawn as it is:
def self.storage_treemap(scope, _filters = {})
{series: [{type: "treemap", data: scope.group(:kind).sum(:bytes).map { |name, value| {name:, value:} }}]}
end
chart :storage_treemap, chart_type: :custom
Area chartsβ
:area takes the same data as :line. :stacked_area and :stacked_horizontal_bar take the multi-series shape, like :stacked_bar:
chart :signups_by_role, chart_type: :stacked_area, title: "Signups by Role"
chart :signups_by_role, chart_type: :stacked_horizontal_bar, title: "Signups by Role"
Area charts fade out below the line in the colour of their series.
Grade gaugesβ
A grade gauge shows one number against coloured bands and names the band it falls in. The data method returns a number, or a one-entry hash to name it:
def self.profile_score(scope, _filters = {})
{"Profile score" => scope.average(:profile_score).to_f.round}
end
chart :profile_score, chart_type: :grade_gauge
By default the range is 0 to 100, split into four equal grades from D to A. Set your own range and grades in chart_attrs. Each grade maps to the highest value it covers:
chart :average_rating,
chart_type: :grade_gauge,
chart_attrs: {
min: 1,
max: 5,
grades: {"Poor" => 2, "Fair" => 3, "Good" => 4, "Excellent" => 5}
}
Bands are coloured from red (lowest grade) to green (highest). To use other colours, override series.axisLine.lineStyle.color through options.
Axis labels, units and coloursβ
These options sit beside chart_type and cover the formatting most charts need:
chart :requests_by_status,
chart_type: :horizontal_bar,
x_label: "Share of requests", # name of the horizontal axis
y_label: "Status", # name of the vertical axis
unit: "%", # appended to labels, the value axis and tooltips
decimals: 1, # round every value
colors: {"Escalated" => "#ee6666", "Completed" => "#3ba272"}
colors maps a name to a colour. For a chart with several series the names are series names; for a single-series pie they are category names. Names you leave out keep the theme's colours.
Zero values in a stacked bar chart and empty pie slices have their labels hidden automatically; the tooltip still shows them.
Highlighting one barβ
highlight: draws one bar of a single-series bar chart in colour, with its value on top, and mutes the others. Pass :max, :min or a category name:
chart "Orders by weekday", chart_type: :bar, highlight: :max do |scope|
scope.group_by_day_of_week(:created_at, format: "%a").count
end
Progress gaugesβ
A :progress_gauge is a ring that fills up to the value, with the value in the middle and a scale of ticks inside. It takes the same data, min and max as a gauge:
chart :repeat_customer_rate, chart_type: :progress_gauge, unit: "%" # {"On track for 80% target" => 68}
Animationβ
Charts use ECharts' own animation. animation: turns it off or tunes it:
chart :users_by_role, chart_type: :donut, animation: false
chart :signups_by_weekday, chart_type: :bar, animation: {duration: 1500, easing: :cubic_out}
duration is in milliseconds, and easing is any ECharts easing such as :linear, :cubic_out or :elastic_out. Both are optional, and an animation: set inside chart_attrs: {options: {...}} takes priority.
Customising a chartβ
chart_attrs takes sizing, orientation and raw ECharts options:
chart :signups_by_role,
chart_type: :stacked_bar,
chart_attrs: {
height: "320px", # default "450px"
width: "100%", # default "100%"
vertical: true, # put the categories on the y axis (horizontal bars)
options: { # any ECharts option, merged over the defaults
legend: {top: 0},
series: {barMaxWidth: 40} # a hash for `series` applies to every series
}
}
options is sent to the browser as JSON, so it cannot contain JavaScript functions directly. Use ECharts' string templates for formatters, for example label: {formatter: "{b}: {c}"}.
When a string template is not enough β a colour lookup or conditional formatting β register a named JavaScript callback in the app's catalyst/custom.js and reference it with Catalyst::Charts.js(:name):
// app/assets/javascripts/catalyst/custom.js
import { registerChartFormatter } from "catalyst/modules/chart_formatters";
registerChartFormatter(
"statusColors",
(params) =>
({
open: "#5470c6",
in_progress: "#fac858",
closed: "#3ba272",
})[params.name] || "#5470c6",
);
chart :cases_by_status, chart_type: :bar, chart_attrs: {
options: {series: {itemStyle: {color: Catalyst::Charts.js(:status_colors)}}}
}
The chart controller swaps each "@name" string for the registered function before the option reaches ECharts β no eval, and an unregistered name logs a warning and stays a literal string. Sentinels work anywhere in options: label.formatter, tooltip.formatter, itemStyle.color, and so on. Host scripts that are not ES modules can call window.Catalyst.registerChartFormatter instead.
Charts on a show pageβ
chart and metric_card also work inside a show_section. There the method is called on the record itself, with no arguments, and returns the same data shapes:
show page_title: :full_name do
tab :profile, "" do
show_section "Insights" do
chart :leave_usage, chart_type: :stacked_horizontal_bar, title: "Leave usage"
end
end
end
# app/models/user.rb
def leave_usage
balances = employee_leave_balances.to_a
[
{name: "Used", data: balances.to_h { |balance| [balance.leave_type_name, balance.used_leaves] }},
{name: "Available", data: balances.to_h { |balance| [balance.leave_type_name, balance.available_balance] }}
]
end
Themesβ
A chart theme is an ECharts theme saved as a JSON file. Catalyst ships with one:
catalyst, used by every chart that names no theme: the admin's brand purple with its positive, warning, informative and error colours, Bootstrap's greys for axes and grid lines, and the admin font.
To add your own:
- Build a theme in the ECharts theme builder and download the JSON version.
- Save it in the host app as
config/catalyst/chart_themes/<name>.json.
Name the theme on the chart:
chart :signups_by_role, chart_type: :stacked_bar, chart_attrs: {theme: :brand}
theme: false draws a chart in ECharts' own default look. A host app theme replaces a bundled theme of the same name, so saving your own catalyst.json restyles every chart at once. Naming a theme that has no file raises an error listing the themes that exist.
A colour in a theme may be written as var(--token, fallback) to take its value from a CSS variable β the bundled theme reads Bootstrap's --fg-body, --fg-1, --fg-3, --fg-4, --bg-body, --border-body, --border-muted and --border-emphasized for its text and line colours this way. The variable is resolved in the browser, so dark-mode aware declarations such as light-dark() work, and the fallback applies where the variable is not defined.
Upgrading from rails_chartsβ
Catalyst no longer depends on the rails_charts gem. Dashboards defined with chart need no changes. If your host app used the gem directly, check for:
line_chart,pie_chartand the otherrails_chartsview helpers in your own views: addrails_chartsto your own Gemfile, or renderCatalyst::UI::Chart::Componentwith an option fromCatalyst::Charts::OptionBuilder.RailsCharts.js(...)formatters inchart_attrs: these now raise an error naming the option. Replace them withunit:,decimals:andcolors:, or with string templates.x_labelandy_labelused to be ignored and are now drawn as axis names.window.RailsCharts.chartsand thechart:renderedevent: these no longer exist.import "echarts"in your own JavaScript: it still resolves, but Catalyst no longer loads it on every page.
Tablesβ
Display tabular data. The first argument is the name of the method that returns the rows; give the heading with title::
row do
section "Tables" do
table :recent_users, title: "Recent Users", associated_model_name: "User" do
column :full_name
column :email
column :status, field_type: :badge, badge_class: { active: "ct-badge-green", disabled: "ct-badge-red" }
column :created_at, field_type: :date, viewable: false
end
end
end
# Receives the permitted records, the active filters and the sort params
def self.recent_users(records, _filters = {}, _sort = {})
records.order(created_at: :desc)
end
Table widgets use the same records table as the index page (Catalyst::UI::RecordsTable::Component), so they share its look and behaviour:
- Sticky header and first column with frozen-column shadows; the widget scrolls inside a fixed-height wrapper
- Columns accept the same options as
indexcolumns βfield_type,badge_class,format,header,viewable, and friends viewable: falsecolumns stay hidden (rendered withd-none, exactly like hidden-by-default columns on the index page), so they never appear on the widget- Pagination renders only when the widget has more than one page; pager links inside a dashboard widget frame reload the widget in place without adding a history entry
- Export is available from the widget toolbar when the model's export permission is granted
Writing dashboard helpersβ
Helper signatureβ
Create custom dashboard helper methods in /app/helpers/catalyst/dashboard_helper.rb:
module Catalyst
module DashboardHelper
# Dashboard helper methods receive (scoped_ar_object, scoped_filters)
# scoped_ar_object is already permission-scoped based on user permissions
def total_users_metric(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object # Already permission-scoped
# Apply dashboard filters
if scoped_filters[:single_select].present?
scoped_filters[:single_select].each do |key, value|
next if value.blank?
base_query = base_query.where(key => value)
end
end
if scoped_filters[:search].present?
search_term = scoped_filters[:search]
base_query = base_query.where("email ILIKE ? OR first_name ILIKE ?",
"%#{search_term}%", "%#{search_term}%")
end
base_query.count
end
def users_by_role_chart_data(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object
# Apply filters similar to above
# ... filter logic ...
base_query.joins(:ct_role).group('ct_roles.name').count
end
end
end
Permission Scopingβ
Dashboard helpers automatically receive permission-scoped data:
- Dashboard-specific permissions: Uses
scope_namefrom permissions with matchingaction_nameandar_model_name - Policy scope fallback: Falls back to
Catalyst::{Model}PolicyIndexScopeif no dashboard-specific scope - Filter integration: Dashboard filters are automatically scoped and passed to helper methods
Filters, permissions and errorsβ
Filter Integrationβ
Dashboard filters are automatically passed to helper methods:
def filtered_users_metric(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object
# Single select filters
if scoped_filters[:single_select]&.dig(:ct_role_id).present?
base_query = base_query.where(ct_role_id: scoped_filters[:single_select][:ct_role_id])
end
# Date filters
if scoped_filters[:date]&.dig(:created_at).present?
date_range = scoped_filters[:date][:created_at]
base_query = base_query.where(created_at: date_range)
end
# Search filters
if scoped_filters[:search].present?
search_term = scoped_filters[:search]
base_query = base_query.where("email ILIKE ?", "%#{search_term}%")
end
base_query.count
end
Permission-Based Scopingβ
Dashboard helpers automatically respect user permissions:
# This helper will only see data the user has permission to access
def department_users_metric(scoped_ar_object, scoped_filters = {})
# scoped_ar_object is already filtered based on:
# 1. Dashboard-specific permission scope (if configured)
# 2. Model policy scope (fallback)
scoped_ar_object.where(department: 'Engineering').count
end
Error Handlingβ
Dashboard helpers include built-in error handling:
def safe_metric_calculation(scoped_ar_object, scoped_filters = {})
begin
# Your calculation logic
scoped_ar_object.complex_calculation
rescue StandardError => e
Rails.logger.error "Dashboard metric error: #{e.message}"
0 # Return safe default value
end
end
Recipesβ
Dashboard with filters, metrics and chartsβ
# app/models/concerns/catalyst/admin/student.rb
module Catalyst
module Admin::Student
extend ActiveSupport::Concern
included do
catalyst do
actions only: []
icon_name 'fa fa-graduation-cap'
dashboard :dashboard_student_type,
display_name: 'Dashboard',
page_title: 'Dashboard',
page_description: 'Student Dashboard' do
# Permissions / access control to be wired into your system:
# - Full Access
# - User Office Only
# - Assignee Only
# Filters - These will be automatically passed to dashboard helpers
filter :office_id,
:multi_select,
helper_method: :select_options_for_office,
placeholder: 'Office',
display_name: 'Office',
active_by_default: true
filter :assigned_to_id,
:multi_select,
helper_method: :select_options_for_lead_assignees,
placeholder: 'Assignee',
display_name: 'Assignee',
active_by_default: true
filter :application_coordinator_id,
:multi_select,
helper_method: :select_options_for_application_coordinators,
placeholder: 'Application Coordinator',
display_name: 'Application Coordinator',
active_by_default: true,
filter_with: :with_application_coordinator_ids
# Row 1 β 3 metric cards (Total Leads | Total Prospects | Total Applications)
row do
section '' do
metric_card :total_leads_metric,
title: 'Total Leads'
end
section '' do
metric_card :total_prospects_metric,
title: 'Total Prospects'
end
section '' do
metric_card :total_applications_metric,
title: 'Total Applications'
end
end
# Row 2 β Leads by Status | Prospects by Status
row do
section '' do
chart :leads_by_status_chart_data,
title: 'Leads by Status',
chart_type: :pie
end
end
row do
section '' do
chart :prospects_by_status_chart_data,
title: 'Prospects by Status',
chart_type: :pie
end
end
# Row 3 β Applications by Status (single column)
row do
section '' do
chart :applications_by_status_chart_data,
title: 'Applications by Status',
chart_type: :pie
end
end
end
index do
page_title 'Students'
# These same filters will be used for dashboard filtering
filter %i[first_name last_name email], :search, placeholder: 'Search'
filter :office_id, :multi_select, helper_method: :select_options_for_office
filter :assigned_to_id, :multi_select, helper_method: :select_options_for_lead_assignees
sort column: "created_at", default: true, default_direction: "desc"
column :full_name
column :email
column :office_name, header: 'Office'
column :status
column :created_at, field_type: :date, format: '%d %b, %Y'
end
end
end
end
end
Helpers for that dashboardβ
Create the dashboard helper methods in /app/helpers/catalyst/dashboard_helper.rb:
module Catalyst
module DashboardHelper
# Metric card methods - receive permission-scoped data and filters
def total_leads_metric(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object.where(status: 'lead')
apply_dashboard_filters(base_query, scoped_filters).count
end
def total_prospects_metric(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object.where(status: 'prospect')
apply_dashboard_filters(base_query, scoped_filters).count
end
def total_applications_metric(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object.where(status: 'application')
apply_dashboard_filters(base_query, scoped_filters).count
end
# Chart data methods
def leads_by_status_chart_data(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object.where(status: 'lead')
filtered_query = apply_dashboard_filters(base_query, scoped_filters)
filtered_query.group(:sub_status).count
end
def prospects_by_status_chart_data(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object.where(status: 'prospect')
filtered_query = apply_dashboard_filters(base_query, scoped_filters)
filtered_query.group(:sub_status).count
end
def applications_by_status_chart_data(scoped_ar_object, scoped_filters = {})
base_query = scoped_ar_object.where(status: 'application')
filtered_query = apply_dashboard_filters(base_query, scoped_filters)
filtered_query.group(:application_status).count
end
private
# Helper method to apply dashboard filters consistently
def apply_dashboard_filters(base_query, scoped_filters)
return base_query if scoped_filters.blank?
# Apply multi-select filters
if scoped_filters[:multi_select].present?
scoped_filters[:multi_select].each do |key, values|
next if values.blank?
case key.to_s
when 'office_id'
base_query = base_query.where(office_id: values)
when 'assigned_to_id'
base_query = base_query.where(assigned_to_id: values)
when 'application_coordinator_id'
base_query = base_query.where(application_coordinator_id: values)
end
end
end
# Apply search filters
if scoped_filters[:search].present?
search_term = scoped_filters[:search]
base_query = base_query.where(
"first_name ILIKE ? OR last_name ILIKE ? OR email ILIKE ?",
"%#{search_term}%", "%#{search_term}%", "%#{search_term}%"
)
end
# Apply date filters
if scoped_filters[:date].present?
scoped_filters[:date].each do |key, date_range|
next if date_range.blank?
base_query = base_query.where(key => date_range)
end
end
base_query
end
end
end
Best Practicesβ
- Use descriptive method names:
total_active_users_metricinstead ofuser_count - Handle empty data gracefully: Return appropriate defaults for empty datasets
- Apply filters consistently: Use the same filter logic across related widgets
- Optimize queries: Use includes, joins, and select to optimize database queries
- Cache expensive calculations: Use Rails caching for complex metrics
- Test with different permission levels: Ensure widgets work for all user types
Security Considerationsβ
- Dashboard helpers automatically receive permission-scoped data
- Filters are validated against dashboard configuration
- All database queries respect user access controls
- Error messages don't expose sensitive information