ruby 28 lines · 1 tab

ActiveRecord callbacks for lifecycle hooks

Alex Kumar Jan 2026
1 tab
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
1 file · ruby Explain with highlit

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

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
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

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
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

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<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)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

ActiveRecord callbacks for lifecycle hooks — share card
Link copied