クイックリファレンス

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

関連するチートシート

関連テーマ