✅
Validations (유효성 검사)
Model 레벨에서 데이터 무결성 보장
Validation은 데이터가 DB에 저장되기 전에 유효성을 검사하는 기능입니다.
class Post < ApplicationRecord
validates :title, presence: true, length: { maximum: 200 }
validates :content, presence: true
validates :slug, uniqueness: true
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
validates :status, inclusion: { in: %w[draft published archived] }
validate :custom_validation_method
private
def custom_validation_method
if publish_date.present? && publish_date < Date.today
errors.add(:publish_date, '과거 날짜는 설정할 수 없습니다')
end
end
end
검증 실패 시:
save→ false 반환save!→ ActiveRecord::RecordInvalid 예외model.errors.full_messages로 에러 메시지 접근뷰에서
@post.errors[:title]로 필드별 에러 표시
핵심 포인트
1
validates :field, 옵션 매크로로 검증 규칙 선언
2
presence: true — 빈 값 불가
3
uniqueness: true — 중복 불가 (DB 인덱스도 추가 권장)
4
length: { minimum: 1, maximum: 200 } — 길이 제한
5
save/create 호출 시 자동으로 검증 실행
6
검증 실패 시 errors 객체에 에러 메시지 저장
장점
- ✓ DB 레벨이 아닌 애플리케이션 레벨에서 검증
- ✓ 에러 메시지 자동 관리
- ✓ 커스텀 검증 메서드 작성 가능
- ✓ 조건부 검증 지원 (if: / unless:)
단점
- ✗ uniqueness는 race condition 가능 → DB unique index 필요
- ✗ 복잡한 비즈니스 규칙은 Service Object로 분리 필요
- ✗ skip_validation이 있어 우회 가능
- ✗ 번역(i18n) 설정이 필요할 수 있음
사용 사례
필수 필드 확인 (presence)
이메일 형식 검증 (format)
중복 방지 (uniqueness)
값 범위 검증 (inclusion, numericality)