[RUBY] Implement user management functionality using Devise

Install Devise

First and foremost, everything starts with installing this gem.

install devise


% gem'devise'
% bundle install
% rails g devise:install

This completes the devise installation.

devise related files

Generate model

rails g devise user

A user model and migration file will be generated.
Also, when this command is executed, devise routing is automatically set in config / routes.rb.

config/routes.rb


Rails.application.routes.draw do
  devise_for :users
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

Generate view

rails g devise:views

When you execute this command, it will automatically generate a view file of the required function in a blink of an eye.

Editing each file

Migration file

This time, the following information will be sent to the table on the new registration screen.

ruby:db/migrate/025412010...


lass DeviseCreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :name,               null: false
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""
      t.string :last_name,          null: false
      t.string :first_name,         null: false
      t.string :kana_last,          null: false
      t.string :kana_first,         null: false
      t.date   :birthday,           null: false
      ... (abridgement)

Now that we have described the information that we designed the table in advance, we can migrate and complete the users table.

% rails db:migrate

Error and validation settings

The form described in the app / views / devise / registrations / new.html.erb file sends a request to the server and is saved in the table, but validation and error message settings are done to save the information correctly. ..

users.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 :name, presence: true
  validates :email, presence: true
  #Variable VALID_PASSWORD_Substitute the option to confuse 6 or more single-byte alphanumeric characters in REGEX
  VALID_PASSWORD_REGEX = /\A(?=.*?[a-z])[a-z\d]{6,}+\z/
  validates :password, presence: true, length: { minimum: 6 }, format: { with: VALID_PASSWORD_REGEX}
  #Describe the option to let the helper input in full-width hiragana, katakana, and kanji
  validates :last_name, :first_name, presence: true, format: { with: /\A(?:\p{Hiragana}|\p{Katakana}|[---]|[one-Storm])+\z/ }
  #Describe the option to input in full-width katakana
  validates :kana_last, :kana_first, presence: true, format: { with: /\A[\p{katakana}---&&[^ -~¡-゜]]+\z/ }
  validates :birthday, presence: true
end

With this, the personal information of the user can be saved in the above form at the time of new registration.

ruby:application.controller.rb


class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :configre_permitted_parameters, if: :devise_controller?

  def configre_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :last_name, :first_name, :kana_last, :kana_first, :birthday])
  end
end

In the configure_permitted_parameters method, which works only when processing the controller related to devise, keys: If the value after is not entered, it can be processed so that it cannot be saved. ** * By the way, devise can receive email and password by default! ** **

Login / out implementation

At this point, all you have to do is implement the login / out function.

-Edit header file

devise/shared/header


#user_signed_in?Set so that the display changes depending on whether you are logged in or not.
      <% if user_signed_in? %>
        <li><%= link_to "#{current_user.name}", class: "user-nickname" %></li>
        <li><%= link_to 'Logout', destroy_user_session_path , method: :delete, class: "logout"%> </li>
      <% else %>
        <li><%= link_to 'Login', new_user_session_path, class: "login" %></li>
        <li><%= link_to 'sign up', new_user_registration_path, class: "sign-up" %></li>
      <% end %>

You can get the name of the logged-in user from the DB column with link_to " # {current_user.name} ".

Now you can log in and register by connecting to localhost: 3000 / users / sign_in or users / sign_up.

Of course, these are file edits related to devie, so please prepare your own controller and try to use these functions from the top page.

If you get an error, you can connect by disconnecting and reconnecting the server, so please try it.

It will be the first public release as a beginner, so if you have a wrong understanding or if you would like to do more like this, we are always looking forward to hearing from you.

Recommended Posts

Implement user management functionality using Devise
Introduce devise in Rails to implement user management functionality
Implement user edit / update function without using devise
Implement search functionality using LIKE clauses
Creating a user authentication function using devise
Implementation of user authentication function using devise (1)
Implementation of user authentication function using devise (3)
devise user registration
Implement user management functions in a wizard format
Implement ProgressBar using library
Flash message using devise
Implement devise edit page
Implement user registration function and corporate registration function separately in Rails devise
[Rails] Implement User search function
Freeters everywhere tried using devise.
Implement category function using ancestory
Memorandum [Rails] User authentication Devise
[Swift] Implement UITableView using xib
Edit user information with Devise