ruby 23 lines · 6 steps

Building a weekly digest email in Rails

A mailer action queries a user's unread notifications, groups them for the view, and skips sending when there's nothing to report.

Explained by highlit
1class DigestMailer < ApplicationMailer
2 default from: "notifications@example.com"
3 
4 def weekly_digest(user)
5 @user = user
6 notifications = user.notifications
7 .unread
8 .includes(:notifiable)
9 .where(created_at: 1.week.ago..Time.current)
10 .order(created_at: :desc)
11 
12 @grouped = notifications.group_by { |n| n.created_at.to_date }
13 @channels = notifications.group_by(&:channel)
14 @total = notifications.size
15 
16 return if @total.zero?
17 
18 mail(
19 to: user.email,
20 subject: "You have #{@total} new #{'notification'.pluralize(@total)}"
21 )
22 end
23end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Chaining scopes with includes avoids N+1 queries when the mail template renders associated records.
  2. 2Precomputing grouped collections in the action keeps view templates simple and logic-free.
  3. 3A guard clause lets a mailer opt out of sending entirely when there's no content worth delivering.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a weekly digest email in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code