LoginSignup
3
5

More than 3 years have passed since last update.

【Rails】ユーザー論理削除の実装

Last updated at Posted at 2020-07-13

目標

ezgif.com-video-to-gif.gif

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

Slim導入
Bootstrap3導入
ログイン機能実装
devise日本語化

実装

1.カラムを追加

ターミナル
$ rails g migration AddIsValidToUsers is_valid:boolean
~_add_is_valid_to_users.rb
class AddIsValidToUsers < ActiveRecord::Migration[5.2]
  def change
    # 「default: true」と「null: false」を追記
    add_column :users, :is_valid, :boolean, default: true, null: false
  end
end
ターミナル
$ rails db:migrate

2.モデルを編集

user.rb
# 追記
enum is_valid: { '有効': true, '退会済': false }

def active_for_authentication?
  super && self.is_valid == '有効'
end

【解説】

① ユーザーの状態をenumで管理する。

enum is_valid: { '有効': true, '退会済': false }

② is_validが有効であればtrueを返すメソッドを定義する。

def active_for_authentication?
  super && self.is_valid == '有効'
end

3.session_controller.rbを編集

session_controller.rb
# 追記
protected

  def reject_user
    user = User.find_by(email: params[:user][:email].downcase)
    if user
      if (user.valid_password?(params[:user][:password]) && (user.active_for_authentication? == true))
        redirect_to new_user_session_path
      end
    end
  end

【解説】

① 入力されたメールアドレスに対応するユーザーが存在するかを確認する。

user = User.find_by(email: params[:user][:email].downcase)

② 入力されたパスワードが正しい場合かつ、2で定義したメソッドの返り値がtrueだった場合は、ログイン処理を行わずにログイン画面に遷移する。

if (user.valid_password?(params[:user][:password]) && (user.active_for_authentication? == true))
  redirect_to new_user_session_path
end

4.ビューを編集

Bootstrap3のアラートコンポーネントを使用してフラッシュメッセージを表示する。

sessions/new.html.slim
/ 追記
- if flash.present?
  .alert.alert-danger.alert-dismissible.fade.in role='alert'
    button.close type='button' data-dismiss='alert'
      span aria-hidden='true'
        | ×
    - flash.each do |name, msg|
      = content_tag :div, msg, :id => 'flash_#{ name }' if msg.is_a?(String)

      p
        a href='#' data-dismiss='alert'
          | 閉じる
3
5
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
3
5