1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails7+Docker】Deviseの導入〜カスタムビューの表示

Last updated at Posted at 2025-07-03

はじめに

この記事では、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によって追加されたルーティング一覧
    • ⚠️ここで記載されているコントローラーはDeviseのデフォルトコントローラーであることに注意

    • sessions(ログイン・ログアウト)
      Image

    • registrations(新規登録)
      Image

    • passwords(パスワードリセット)
      Image

カスタムビューの生成

docker compose exec web rails generate devise:views users

一部moduleを使いたい場合は、vflagの後ろで指定する。

# 例: ログイン/ログアウト(sessions), ユーザー登録(registrations)のみカスタムビューを作成したい時
docker compose exec web rails generate devise:views users -v sessions registrations

⚠️この段階ではまだブラウザ上に表示されるのはDeviseのデフォルトビューになります。この後、カスタムコントローラーを生成し、ルーティング設定することで、カスタムビューがブラウザ上で表示されるようになります。

  • 上記コマンド(指定なし)を実行した際に生成されたビュー一覧(app/views/users以下)
    Image

  • ユーザー認証に関わる主要なViewファイル

    • ログイン画面(http://localhost:3000/users/sign_in)
      Viewファイルの相対パス: app/views/users/sessions/new.html.erb
      Image

    • 新規登録画面(http://localhost:3000/users/sign_up)
      Viewファイルの相対パス: app/views/users/registrations/new.html.erb
      Image

    • パスワードリセット画面(http://localhost:3000/users/password/new)
      Viewファイルの相対パス: app/views/users/passwords/new.html.erb
      Image

    • エラーメッセージパーシャル
      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を使いたい場合は、cflagの後ろで指定する。

# 例: ログイン/ログアウト(sessions), ユーザー登録(registrations)のみカスタムコントローラーを作成したい時
docker compose exec web rails generate devise:controllers users -c sessions registrations
  • 上記コマンド(指定なし)を実行した際に生成されたコントローラー一覧(app/controllers/users以下)
    Image

ルーティングの変更

# 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フィールドも許可されていることがわかります。
Image

参考資料

Deviseの公式README

Deviseで扱うmoduleについての公式ドキュメント

Rails: Deviseを徹底理解する(1)基礎編(翻訳)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?