🪝

Model Callbacks

저장/삭제 전후에 자동 실행되는 훅

Model Callback은 ActiveRecord 객체의 생성, 수정, 삭제 등 라이프사이클 이벤트에 맞춰 자동으로 실행되는 메서드입니다.

주요 콜백 순서 (create):
1. before_validation
2. after_validation
3. before_save
4. before_create
5. after_create
6. after_save
7. after_commit (트랜잭션 커밋 후)

class Post < ApplicationRecord
  before_save :normalize_title
  after_create :send_notification
  before_destroy :check_dependencies

  private

  def normalize_title
    self.title = title.strip.titleize
  end

  def send_notification
    NotificationJob.perform_later(self)
  end
end

주의: 콜백이 너무 많으면 코드 흐름 파악이 어려워지고, 테스트도 복잡해집니다. 복잡한 비즈니스 로직은 Service Object로 분리하는 것이 좋습니다.

핵심 포인트

1

before_validation — 검증 전 데이터 정규화

2

after_validation — 검증 후 추가 처리

3

before_save / before_create / before_update — 저장 전 로직

4

after_save / after_create / after_update — 저장 후 로직

5

before_destroy / after_destroy — 삭제 전후 로직

6

after_commit — 트랜잭션 완료 후 (외부 API 호출, Job 실행에 적합)

장점

  • 반복 코드 줄임 (DRY)
  • 데이터 일관성 보장
  • 라이프사이클 이벤트에 자동 대응
  • 선언적이라 의도 파악 쉬움

단점

  • 과도한 콜백은 코드 추적 어려움
  • 콜백 순서 의존성 발생 가능
  • 테스트 시 의도치 않은 부수효과
  • Service Object가 더 적합한 경우가 많음

사용 사례

데이터 정규화 (before_save) 알림 발송 (after_create) UUID 자동 생성 (before_create) 감사 로그 기록 (after_save) 연관 데이터 정리 (before_destroy)