ruby 41 lines · 8 steps

A guarded destroy action in Rails

A namespaced admin controller deletes an account only after confirmation, protection, and transactional safety checks.

Explained by highlit
1class Admin::AccountsController < Admin::BaseController
2 before_action :set_account, only: :destroy
3 
4 def destroy
5 if params[:confirm_name] != @account.name
6 redirect_to admin_account_path(@account),
7 alert: "Type the account name exactly to confirm deletion."
8 return
9 end
10 
11 if @account.protected?
12 redirect_to admin_account_path(@account),
13 alert: "This account is protected and cannot be deleted."
14 return
15 end
16 
17 @account.transaction do
18 @account.memberships.destroy_all
19 @account.destroy!
20 end
21 
22 AccountAuditLog.record!(
23 action: :destroyed,
24 target: @account,
25 actor: current_admin,
26 metadata: { name: @account.name }
27 )
28 
29 redirect_to admin_accounts_path,
30 notice: "Account #{@account.name} was permanently deleted."
31 rescue ActiveRecord::RecordNotDestroyed => e
32 redirect_to admin_account_path(@account),
33 alert: "Could not delete account: #{e.message}"
34 end
35 
36 private
37 
38 def set_account
39 @account = Account.find(params[:id])
40 end
41end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Guard clauses with early returns keep destructive actions readable by rejecting bad requests before any mutation happens.
  2. 2Wrapping dependent deletions in a transaction ensures the record and its associations are removed atomically or not at all.
  3. 3Recording an audit log after a successful destroy preserves accountability for irreversible operations.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A guarded destroy action in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code