1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails備忘録】ユーザー管理機能を実装する手順まとめ(devise・バリデーション・日本語化・RSpecテスト)

Posted at

はじめに

本記事では、Railsアプリにおける「ユーザー管理機能(新規登録・ログイン)」の実装手順を、復習と備忘録を兼ねてまとめます。
ユーザー管理にはdeviseを利用するので、devise導入からバリデーション、日本語化、テストまで一通りの流れになります。


1. deviseの導入

Gemfile

gem 'devise'

コマンド

bundle install
rails generate devise:install

解説:

  • deviseはユーザー認証の定番gemで、インストール後にセットアップコマンドで初期設定ファイルが生成される

2. Userモデルの作成

コマンド

rails generate devise User
rails db:migrate

解説:

  • devise用のUserモデル・テーブルを自動生成
  • db/migrate/配下のマイグレーションでusersテーブルが作られる

3. Userモデルのバリデーション追加

ファイル: user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  # バリデーションを追加
  validates :nickname, :last_name, :first_name, :last_kana, :first_kana, :birthday, presence: true

  # パスワードのバリデーション
  validates :password, format: { with: /\A(?=.*?[a-z])(?=.*?\d)[a-z\d]+\z/i, message: 'は半角英数字を両方含む必要があります' }, allow_nil: true

  # 名前(全角)のバリデーション
  validates :last_name, :first_name, format: { with: /\A[ぁ-んァ-ヶ一-龥々ー]+\z/, message: 'は全角(漢字・ひらがな・カタカナ)で入力してください' }

  # 名前カナ(全角)のバリデーション
  validates :last_kana, :first_kana, format: { with: /\A[ァ-ヶー]+\z/, message: 'は全角(カタカナ)で入力してください' }
end

解説:

  • deviseの標準バリデーションに加え、独自の必須・形式バリデーションを追加
  • 日本語名・カナ名・生年月日・パスワード形式などをチェック

4. 新規登録・ログイン画面のカスタマイズ

ファイル:

  • app/views/devise/registrations/new.html.erb
  • app/views/devise/sessions/new.html.erb

ポイント:

  • フォーム項目を追加・日本語化
  • f.text_field :nickname など、Userモデルの属性に合わせてフォームを編集

5. 日本語化(エラーメッセージ・属性名)

ファイル: ja.yml

ja:
  activerecord:
    attributes:
      user:
        nickname: "ニックネーム"
        email: "メールアドレス"
        password: "パスワード"
        last_name: "姓"
        first_name: "名"
        last_kana: "姓(カタカナ)"
        first_kana: "名(カタカナ)"
        birthday: "生年月日"
  errors:
    format: "%{attribute} %{message}"
    messages:
      blank: "を入力してください"
      # ...他

解説:

  • 属性名を日本語化し、バリデーションエラーも日本語で表示
  • deviseのエラーメッセージもdevise.ja.ymlで日本語化可能

6. RSpecによるモデルテスト

ファイル: spec/models/user_spec.rb

RSpec.describe User, type: :model do
  before { @user = FactoryBot.build(:user) }

  context '登録できる場合' do
    it '全ての項目が正しく入力されていれば登録できる' do
      expect(@user).to be_valid
    end
    # ...正常系
  end

  context '登録できない場合' do
    it 'ニックネームが空では登録できない' do
      @user.nickname = ''
      @user.valid?
      expect(@user.errors.full_messages).to include("ニックネーム を入力してください")
    end
    # ...異常系(メール重複、パスワード形式、名前形式など)
  end
end

解説:

  • FactoryBotでテスト用ユーザーを生成
  • 正常系・異常系をcontextで分けてテスト
  • エラーメッセージは日本語・属性名付きで検証

7. コントローラー・ルーティング

ファイル:

  • config/routes.rb
    devise_for :users
    
  • app/controllers/application_controller.rb
    before_action :configure_permitted_parameters, if: :devise_controller?
    
    def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:sign_up, keys: [:nickname, :last_name, :first_name, :last_kana, :first_kana, :birthday])
    end
    

解説:

  • deviseのルーティング・ストロングパラメータ拡張
  • 新規登録時に追加項目も保存できるようにする

8. 動作確認

  • 新規登録・ログイン・ログアウトが正常に動作するか確認
  • バリデーション・エラーメッセージが日本語で表示されるか確認
  • RSpecテストがすべてパスすることを確認

まとめ

  • deviseでユーザー管理機能を簡単・安全に実装
  • RSpecでテストも忘れずに実施
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?