guest@websec: ~/websec/r05-model-callbacks — zsh — 100×40 by SaKKo YouTube ENTH

guest@websec ~ % man r05-model-callbacks

Model Callbacks

Callbacks are methods Active Record calls for you at fixed moments in a record's life: before it's validated, after it's saved, after the transaction commits. Knowing the exact order is the difference between a neat default value and a production bug.

Compute defaults that validations need in before_validation, trigger external side effects (jobs, webhooks, emails) in after_commit so rolled-back transactions never leak outside, and remember that update_columns (including soft_delete!) skips standard save callbacks.

Registering a callback

class User < ApplicationRecord
  before_validation :initialize_authentication_token, on: [:create]   # method name + options
  after_soft_delete :cascade_soft_delete                              # custom callback (see below)
end

class Role < ApplicationRecord
  after_commit :broadcast_webhook_event
  before_save :strip_name, if: :name_changed?                         # conditional
  after_create_commit -> { Rails.logger.info("role #{id} created") }  # a block works too
end

Options: on: (:create, :update, or a custom validation context), if: / unless: (a method name or lambda), prepend: true (run before callbacks declared earlier).

Every callback, in order

createupdatedestroy
before_validationbefore_validationbefore_destroy
after_validationafter_validationaround_destroy
before_savebefore_saveDELETE
around_savearound_saveafter_destroy
before_createbefore_updateafter_commit / after_rollback
around_createaround_update
INSERTUPDATE
after_createafter_update
after_saveafter_save
after_commit / after_rollbackafter_commit / after_rollback

Plus: after_initialize (every new and every record loaded), after_find (every record loaded, before after_initialize), after_touch. Commit shortcuts: after_create_commit, after_update_commit, after_destroy_commit, after_save_commit.

explorer: which callbacks fire?pick an operation and a scenario

Things to notice: the database write sits in the middle; after_save runs before the commit; a failure anywhere before COMMIT undoes everything; and soft_delete! / update_columns skip almost all of it.

Callbacks in our code

before_validation, on: :create

class ClientApplication < ApplicationRecord
  before_validation :generate_credentials, on: :create

  validates :name, :app_key, :api_secret, presence: true
  validates :app_key, uniqueness: true
  ...

Why before_validation and not before_create? Because before_create runs after validation, and the presence check on app_key would fail first. Generate values that validations depend on in before_validation.

after_commit

class Role < ApplicationRecord
  after_commit :broadcast_webhook_event

  def broadcast_webhook_event
    return if client_application.nil?

    event_type = determine_event_type          # created / updated / destroyed
    return if event_type.nil?
    # ignore saves where only updated_at changed
    return if event_type == "role.updated" && previous_changes.except("updated_at").empty?

    client_application.notify_webhook(event_type, role_payload)   # -> perform_later
  end

  def determine_event_type
    if destroyed? || deleted_at.present? then "role.destroyed"
    elsif previously_new_record? then "role.created"
    else "role.updated"
    end
  end
end

Side effects that leave the database (jobs, webhooks, emails) belong in after_commit. In after_save the transaction is still open: the job could start before the row is visible, or the transaction could roll back after the webhook is already sent. previous_changes and previously_new_record? tell you what just happened.

Gotcha: soft_delete! writes with update_columns, which skips after_commit. So the "role.destroyed" branch above never runs on a soft delete. If a client must hear about deletions, call broadcast_webhook_event from after_soft_delete. Try role.soft_delete! in the explorer above.

Custom callbacks: define_model_callbacks

module SoftDeletable
  included do
    define_model_callbacks :soft_delete, :restore    # creates before_/around_/after_soft_delete etc.
    after_soft_delete :execute_cascade_soft_delete
    after_restore :execute_cascade_restore
    validate :ensure_unique_attributes_on_restore, on: :restore   # custom validation context
  end

  def soft_delete!
    return false if soft_deleted?
    run_callbacks :soft_delete do                     # before_* ... block ... after_*
      update_columns(deleted_at: Time.current, updated_at: Time.current)
    end
    true
  end

  def restore(context: :restore)
    self.deleted_at = nil
    return false unless valid?(context)               # runs validations tagged on: :restore
    run_callbacks(:restore) { update_columns(deleted_at: nil, updated_at: Time.current) }
    true
  end
end

define_model_callbacks gives your own operations the same before_/around_/after_ hooks as save. Validation contexts (valid?(:restore)) let one validation run only for one operation: here, restoring a user whose username was taken while they were deleted fails cleanly.

Normalizing input: a writer, not a callback

def permissions=(values)
  super(Array(values).compact.map(&:to_s).sort)   # always a sorted array of strings
end

Overriding the attribute writer normalizes the value the moment it’s assigned, so validations and changed? see the clean value. Rails 7.1+ also has normalizes :email, with: -> { _1.strip.downcase } for the same job.

Halting and skipping

before_destroy :ensure_not_last_admin

def ensure_not_last_admin
  return unless is_admin? && User.where(is_admin: true).count == 1
  errors.add(:base, "Cannot remove the last admin")
  throw :abort                     # stops the chain; destroy returns false / destroy! raises
end

These methods skip callbacks and validations entirely. Use them on purpose, never by accident:

update_column · update_columns · update_all · delete · delete_all · delete_by · insert / insert_all · upsert / upsert_all · increment! · decrement! · touch_all · update_counters

Rules of thumb

  • Callbacks should be about this record: defaults, generated keys, normalized values, cascading soft deletes.
  • Anything that leaves the process (HTTP, email, webhooks) goes in after_commit, and usually just enqueues a job.
  • Never call slow external services in before_* or after_save: they hold the database transaction open.
  • If a callback needs to know who did something or which endpoint was called, it belongs in the controller or a service instead.

Check yourself

You need to email the user after their account is created. Which callback?

After commit, the user row is guaranteed to exist for the mail job. Enqueue with deliver_later.

before_create :set_code sets a value that validates :code, presence: true checks. Saving fails with "Code can't be blank". Why?

Move it to before_validation :set_code, on: :create, like generate_credentials.