はじめに
この記事では、Dockerを使ったRails開発環境において、認証機能ライブラリ Devise を導入し、ブラウザ上でカスタムビューを表示するまでの手順を解説します。
基本的には、Devise公式READMEの "Getting started" に沿って進めつつ、必要なカスタマイズやハマりやすいポイントも補足しています。
この記事を読むとできること
- Deviseの基本的な認証機能(ユーザー登録・ログイン/ログアウト・パスワードリセットなど)を実現する
- Deviseのデフォルトビューを自作のカスタムビューに置き換えて表示する
- Strong Parametersの設定を変更し、
name
などのカスタムフィールドを登録フォームで扱えるようにする
開発環境
- macOS: Sequoia 15.1.1
- Ruby: 3.3.6
- Rails: 7.2.2.1
- Docker
実装手順
Dockerコンテナを起動
docker compose up
gem devise
をGemfileに追加してバンドル
docker compose exec web bundle add devise
Deviseをインストール
docker compose exec web rails generate devise:install
Userモデルを作成
docker compose exec web rails generate devise user
- ルーティングファイルに自動的に
devise_for :users
が追加される。# config/routes.rb Rails.application.routes.draw do devise_for :users root "posts#index" end
生成されたマイグレーションファイルにname(string型)を追加
# db/migrate/20250701074658_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration[7.2]
def change
create_table :users do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
t.string :name, null: false, default: ""
.
.
.
マイグレーション実行
docker compose exec web rails db:migrate
コンテナを再起動
docker compose restart
⚠️アプリを再起動しないと、ルーティングが未定義などのエラーが出てしまうので注意!
参照: https://github.com/heartcombo/devise/blob/main/README.md#getting-started
You should restart your application after changing Devise's configuration options (this includes stopping spring). Otherwise, you will run into strange errors, for example, users being unable to login and route helpers being undefined.
- ここでようやくルーティングが正しく設定されます。
devise_for :users
によって追加されたルーティング一覧
カスタムビューの生成
docker compose exec web rails generate devise:views users
一部moduleを使いたい場合は、v
flagの後ろで指定する。
# 例: ログイン/ログアウト(sessions), ユーザー登録(registrations)のみカスタムビューを作成したい時
docker compose exec web rails generate devise:views users -v sessions registrations
⚠️この段階ではまだブラウザ上に表示されるのはDeviseのデフォルトビューになります。この後、カスタムコントローラーを生成し、ルーティング設定することで、カスタムビューがブラウザ上で表示されるようになります。
-
ユーザー認証に関わる主要なViewファイル
-
ログイン画面(
http://localhost:3000/users/sign_in
)
Viewファイルの相対パス:app/views/users/sessions/new.html.erb
-
新規登録画面(
http://localhost:3000/users/sign_up
)
Viewファイルの相対パス:app/views/users/registrations/new.html.erb
-
パスワードリセット画面(
http://localhost:3000/users/password/new
)
Viewファイルの相対パス:app/views/users/passwords/new.html.erb
-
エラーメッセージパーシャル
Viewファイルの相対パス:app/views/users/shared/_error_messages.html.erb
-
リンクパーシャル
Viewファイルの相対パス:app/views/users/shared/_links.html.erb
-
カスタムコントローラーの生成
docker compose exec web rails generate devise:controllers users
一部moduleを使いたい場合は、c
flagの後ろで指定する。
# 例: ログイン/ログアウト(sessions), ユーザー登録(registrations)のみカスタムコントローラーを作成したい時
docker compose exec web rails generate devise:controllers users -c sessions registrations
ルーティングの変更
# config/routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: {
registrations: 'users/registrations',
sessions: 'users/sessions',
confirmations: 'users/confirmations',
passwords: 'users/passwords',
unlocks: 'users/unlocks'
}
root "posts#index"
end
- ここまで行うと、カスタムビューがブラウザ上に表示されます。
ユーザー登録画面にname
フィールドを追加
# app/views/users/registrations/new.html.erb
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= render "users/shared/error_messages", resource: resource %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name, autofocus: true, autocomplete: "name" %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autocomplete: "email" %>
</div>
.
.
.
Strong Parametersにname
フィールドを追加
Deviseでカスタムフィールド(今回の場合はname
)を追加した場合、Strong Parametersの設定が必要です。
これが設定されていないと、フォームから送信されたnameの値が無視されて、name=""の状態でユーザーが作成されてしまいます。
Deviseのアクションsign_in
, sign_up
, account_update
ではデフォルトでname
フィールドが許可されていないので、明示的にdevise_parameter_sanitizer.permit
で許可する必要があります。
参照: https://github.com/heartcombo/devise/blob/main/README.md#strong-parameters
There are just three actions in Devise that allow any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and default permitted parameters are:
- sign_in (Devise::SessionsController#create) - Permits only the authentication keys (like email)
- sign_up (Devise::RegistrationsController#create) - Permits authentication keys plus password and password_confirmation
- account_update (Devise::RegistrationsController#update) - Permits authentication keys plus password, password_confirmation and current_password
具体的には以下のようにコントローラーを修正します。
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has.
allow_browser versions: :modern
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
end
end
Strong Parametersの設定を変更したことにより、ユーザー作成の際にnameフィールドも許可されていることがわかります。
参考資料
Deviseの公式README
Deviseで扱うmoduleについての公式ドキュメント
Rails: Deviseを徹底理解する(1)基礎編(翻訳)