[Ruby] [Rails] Implementation of user logical deletion

1 minute read

Target

ezgif.com-video-to-gif.gif

Development environment

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

Premise

Implemented below.

Slim introductionBootstrap3 installedImplementation of login function

Implementation

1. Add a column

terminal


$ rails g migration AddIsValidToUsers is_valid:boolean
class AddIsValidToUsers <ActiveRecord::Migration[5.2]
  def change
# Added "default: true" and "null: false"
    add_column :users, :is_valid, :boolean, default: true, null: false
  end
end

terminal


$ rails db:migrate

2. Edit the model

user.rb


# Addition
enum is_valid: {'valid': true,'leaved': false}

def active_for_authentication?
  super && self.is_valid =='valid'
end

[Explanation]

① Manage user status with enum.

enum is_valid: {'valid': true,'leaved': false}

② Define a method that returns true if is_valid is valid.

def active_for_authentication?
  super && self.is_valid =='valid'
end

3. Edit the session_controller.rb

session_controller.rb


# Addition
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

[Explanation]

① Check if there is a user corresponding to the entered email address.

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

② If the entered password is correct and the return value of the method defined in 2 is true, transition to the login screen without performing login processing.

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

4. Edit view

Use the Alerts component of Bootstrap3 to display flash messages.

sessions/new.html.slim


/ Addendum
- 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'
          | Close