빠른 참조

Devise 치트시트 (Ruby on Rails 인증 솔루션)

Ruby on Rails의 표준 인증 솔루션 Devise 핵심 치트시트. 제너레이터, 모델 모듈 구성, 컨트롤러 헬퍼, 뷰 커스터마이징 및 라우팅을 정리합니다.

· 게시일

Devise는 Warden을 기반으로 구축된 유연하고 모듈화된 Ruby on Rails 표준 인증 솔루션입니다.

설치 및 코드 생성기 (Installation & Generators)

# Add gem to Gemfile and bundle
bundle add devise

# Install Devise configuration initializer
rails generate devise:install

# Generate Devise model (e.g. User or Admin)
rails generate devise User
rails db:migrate

# Generate editable views
rails generate devise:views

컨트롤러 및 뷰 헬퍼 (Controller & View Helpers)

# Protect controller actions with before_action
before_action :authenticate_user!

# Status checks
user_signed_in?
current_user
user_session

# URL and Path Helpers
new_user_session_path           # Login form
destroy_user_session_path       # Logout (DELETE)
new_user_registration_path      # Sign up form
edit_user_registration_path     # Edit account settings
new_user_password_path          # Password reset request

모델 모듈 목록 (Model Modules)

class User < ApplicationRecord
  devise :database_authenticatable, # Hashes and stores passwords in DB
         :registerable,           # Sign up, edit, and destroy accounts
         :recoverable,            # Resets password and sends reset instructions
         :rememberable,           # Manages cookies to remember user sessions
         :trackable,              # Tracks sign in count, timestamps, and IP addresses
         :validatable,            # Validates email and password length/presence
         :confirmable,            # Sends verification emails with tokens
         :lockable,               # Locks accounts after failed login attempts
         :timeoutable             # Expires inactive sessions after set duration
end

인증 상태별 조건부 라우팅 (Scoped Routing)

Rails.application.routes.draw do
  devise_for :users

  # Custom route scopes based on authentication status
  authenticated :user do
    root to: 'dashboard#index', as: :authenticated_root
  end

  unauthenticated do
    root to: 'home#index'
  end
end

관련 치트시트

관련 주제