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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Choosing the right dependent: option per association encodes your data-integrity rules directly in the model.
- 2Wrapping state changes and side effects in a transaction keeps the record and its notifications consistent.
- 3A before_destroy callback that throws :abort lets you veto deletion while surfacing a user-facing error.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
ruby
require "csv" def parse_transaction_row(line) fields = CSV.parse_line(line, headers: false, skip_blanks: true)
Parsing one CSV transaction row in Ruby
parsing
type-coercion
error-handling
Intermediate
6 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/safely-closing-an-account-in-rails-explained-ruby-7419/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.