ruby 32 lines · 9 steps

Safely closing an Account in Rails

An Active Record model coordinates cascading cleanup, a destroy guard, and a transactional closure workflow.

Explained by highlit
1class Account < ApplicationRecord
2 has_many :projects, dependent: :destroy_async
3 has_many :memberships, dependent: :destroy_async
4 has_many :invoices, dependent: :restrict_with_error
5 has_one :billing_profile, dependent: :destroy_async
6 
7 before_destroy :ensure_no_open_balance
8 
9 scope :dormant, -> { where(last_active_at: ..90.days.ago) }
10 
11 def schedule_closure!(reason:)
12 transaction do
13 update!(status: :closing, closure_reason: reason, closed_at: Time.current)
14 AccountClosedMailer.with(account: self).confirmation.deliver_later
15 end
16 
17 destroy
18 end
19 
20 private
21 
22 def ensure_no_open_balance
23 return if outstanding_balance.zero?
24 
25 errors.add(:base, "cannot close an account with an outstanding balance")
26 throw :abort
27 end
28 
29 def outstanding_balance
30 invoices.unpaid.sum(:amount_cents)
31 end
32end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Choosing the right dependent: option per association encodes your data-integrity rules directly in the model.
  2. 2Wrapping state changes and side effects in a transaction keeps the record and its notifications consistent.
  3. 3A before_destroy callback that throws :abort lets you veto deletion while surfacing a user-facing error.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Safely closing an Account in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code