class DashboardMetrics
include ActiveModel::Model
attr_reader :account
def initialize(account)
@account = account
end
def summary
scope = account.orders
row = scope.reorder(nil).pick(
Arel.sql("COALESCE(SUM(total_cents), 0)"),
Arel.sql("COUNT(*)"),
Arel.sql("COUNT(*) FILTER (WHERE status = 'refunded')")
)
{
gross_cents: row[0],
order_count: row[1],
refunded_count: row[2]
}
end
def cache_key_with_version
"dashboard/#{account.id}-#{fingerprint}"
end
def cache_key
"dashboard/#{account.id}"
end
private
def fingerprint
stamp, count = account.orders.pick(
Arel.sql("MAX(updated_at)"),
Arel.sql("COUNT(*)")
)
"#{count}-#{stamp&.utc&.to_fs(:usec)}"
end
end
class DashboardsController < ApplicationController
before_action :authenticate_user!
def show
@account = current_user.account
@metrics = DashboardMetrics.new(@account)
end
end
<h1>Dashboard for <%= @account.name %></h1>
<%% cache @metrics, expires_in: 1.hour do %>
<%% summary = @metrics.summary %>
<section class="metrics">
<div class="metric">
<span class="label">Gross revenue</span>
<span class="value"><%= number_to_currency(summary[:gross_cents] / 100.0) %></span>
</div>
<div class="metric">
<span class="label">Orders</span>
<span class="value"><%= number_with_delimiter(summary[:order_count]) %></span>
</div>
<div class="metric">
<span class="label">Refunded</span>
<span class="value"><%= number_with_delimiter(summary[:refunded_count]) %></span>
</div>
</section>
<p class="generated-at">Computed at <%= Time.current.to_fs(:short) %></p>
<%% end %>
This snippet shows how an expensive analytics query that powers a dashboard is cached with Rails fragment caching, keyed so that the cache expires automatically when the underlying data changes. The core idea is to never manually delete cache entries; instead the cache key embeds a version derived from the data, so a stale key is simply never read again and the old fragment ages out on its own.
In DashboardMetrics model, the heavy aggregation lives in #summary, which runs a single grouped SUM/COUNT over orders scoped to the account. That query is genuinely expensive, so the value most worth caching is the computed hash. The method #cache_key_with_version is the crux: it combines the account id, the latest orders.updated_at, and the row count. Because the maximum updated_at moves whenever any order is created or touched, and the count moves on inserts and deletes, the composite key changes exactly when the results could change. This is the same principle behind Rails' cache_versioning — the key is a fingerprint of the data, not a timestamp guess.
The DashboardsController fetches metrics but does no caching itself; caching is a view concern here, keeping the controller thin. It passes the plain object to the template.
In dashboard/show.html.erb, the cache helper wraps the expensive fragment and is handed @metrics directly. Rails calls cache_key_with_version on the object to build the fragment key, so the ERB block — including the call to metrics.summary — only executes on a miss. On subsequent requests with unchanged data, Rails serves the stored HTML and the SQL never runs. A one-hour expires_in acts as a safety net against unbounded growth.
The trade-off is a small MAX(updated_at)/COUNT(*) probe on every request, which is far cheaper than the full aggregation and cheaper than rendering. A pitfall to watch: aggregates that depend on other tables (say refunds) must also feed the key, or the fragment can go stale. This pattern shines for read-heavy dashboards where writes are comparatively rare, and pairs naturally with Russian-doll caching when the summary is composed of nested cached pieces.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
Share this code
Here's the card — post it anywhere.