class User < ApplicationRecord
has_many :posts, foreign_key: :author_id, dependent: :destroy
before_validation :normalize_email
before_create :generate_auth_token
after_create :send_welcome_email
before_destroy :archive_content
validates :email, presence: true, uniqueness: { case_sensitive: false }
private
def normalize_email
self.email = email.to_s.downcase.strip
end
def generate_auth_token
self.auth_token = SecureRandom.hex(32)
end
def send_welcome_email
SendWelcomeEmailWorker.perform_async(id)
end
def archive_content
posts.update_all(archived_at: Time.current, archived_by_user_id: id)
end
end
Callbacks hook into the ActiveRecord lifecycle to execute code before or after operations like create, update, or destroy. I use before_validation to normalize data (like downcasing emails), after_create to trigger welcome emails, and before_destroy to clean up associated resources. The key discipline is keeping callbacks focused on model-level concerns rather than business logic—complex workflows belong in service objects. I avoid callbacks that trigger external API calls or send emails directly, instead enqueueing background jobs. Callbacks can make debugging difficult when they're overused, so I prefer explicit service objects for orchestration and reserve callbacks for truly universal model behaviors. I also use prepend: true when callback order matters.
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
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<form data-controller="query-sync" data-action="change->query-sync#apply">
<select name="status" class="rounded border p-2">
<option value="">Any</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
Filter UI that syncs query params via Stimulus (no front-end router)
Share this code
Here's the card — post it anywhere.