[Ruby] [Rails] Implementation of user withdrawal function

1 minute read

Hello, this is tt_tsutsumi.
This time I would like to implement the user withdrawal function.
I hope this article helps somebody.

I would like to write articles about new user registration and editing from time to time.
This time, we will implement the user withdrawal function and prevent the withdrawn users from logging in.

1. Definition of membership status

Set the member status of the user with enum (boolean type).
The boolean type is a type that saves boolean values, and only two situations can be registered.
This time, we will use this type because the user has two choices: ** valid member or withdrawn member **.
Also, if ** is_active ** is ** true (valid member) **, set to log in.

  • If ** is_active ** is ** false (withdrawn member) **, you will not be able to log in.

user.rb


    enum is_active: {Available: true, Invalid: false}
    #True for valid members, false for withdrawn members

    def active_for_authentication?
        super && (self.is_active === "Available")
    end
    #is_If active is valid, a valid member(You can log in)

2. Description of route

routes.rb


    resources :users do
        member do
            get "check"
            #Get user membership status
            patch "withdrawl"
            #Update user membership status
        end
    end

3. Create an action

Next, create an action on the controller.

  • This time, we also created a page to confirm withdrawal, so there are two actions.

users_controller



def check
    @user = User.find(params[:id])
    #Find user information
end

def withdrawl
    @user = User.find(current_user.id)
    #The currently logged in [email protected] in user
    @user.update(is_active: "Invalid")
    #Change registration information to Invalid with update
    reset_session
    #Reset sessionID
    redirect_to root_path
    #Path to the specified root
end

private

def user_params
    params.require(:user).permit(:active)
end

Create a link and unsubscribe the user.
Since method is updated instead of deleted, it will be described as patch.

ruby:withdrawl.html.erb



<div class="withdrawl">
    <%= link_to "Withdrawal", withdrawl_user_path(@user.id), method: :patch %>
</div>

Now you can implement the user withdrawal function and prevent unsubscribed users from logging in.
Thank you for visiting !!