[Beginner] How to use devise Change settings from introduction

Introduction

I used devise for studying and created a login area. By default, the user name and password are used for authentication, but this time we will change the settings to authenticate with the employee number and password.

environment

Ruby 2.5.3 Ruby on Rails 5.2.4 Devise 4.7.1

Complete

スクリーンショット 2020-06-24 16.00.39.png スクリーンショット 2020-06-24 16.00.56.png I've adjusted the appearance with bootstrap, but I will change the settings so that it looks like this. # Implementation

Gemfile


gem 'devise'
$ bundle install

● devise settings

$ rails generate devise:install

I get a message like this. Since I am a beginner, I was surprised at the error message, but if this appears, it is a success.

create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================
 
Some setup you must do manually if you haven't yet:
 
  1. Ensure you have defined default url options in your environments files. Here
 	is an example of default_url_options appropriate for a development environment
 	in config/environments/development.rb:
 
   	config.action_mailer.default_url_options = { :host => 'localhost:3000' }
 
 	In production, :host should be set to the actual host of your application.
 
  2. Ensure you have defined root_url to *something* in your config/routes.rb.
 	For example:
 
   	root :to => "home#index"
 
  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
 	For example:
 
   	<p class="notice"><%= notice %></p>
   	<p class="alert"><%= alert %></p>
 
  4. You can copy Devise views (for customization) to your app by running:
 
   	rails g devise:views
 
===============================================================================

● Message content

  1. When you send an authentication email such as new registration, set the approval link URL in the text of the email.

config/environments/development.rb


config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  1. Route setting It is set to jump to the route after registering as a member.

  2. Embed a flash message. It is used when you want to display the flash when logging in or out. I embedded it in a common view.

app/views/layouts/application.html.erb


<body>
 <p class="notice"><%= notice %></p>
 <p class="alert"><%= alert %></p>
</body>
  1. To customize the view
$ rails g devise:views

● Change devise settings

config/initializers/devise.rb


Around the 43rd line
Specify the employee number for the authentication key
- config.authentication_keys = [:email]
+ config.authentication_keys = [:employee_number]
Around the 55th line
Authentication key values are not case sensitive
- config.case_insensitive_keys = [:email]
+ config.case_insensitive_keys = [:employee_number]
Around the 60th line
Get rid of spacebar
- config.strip_whitespace_keys = [:email]
+ config.strip_whitespace_keys = [:employee_number]

● Create a user model

$ rails g devise user

app/models/user.rb


#The following three methods use the user name as the authentication key, so
#Overriding and disabling unnecessary methods.

def email_required?
    false
  end

  def email_changed?
    false
  end
  
  def will_save_change_to_email?
    false
  end

db/migrate/date_devise_create_user.rb



class DeviseCreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :employee_number,    null: false, default: ""
      t.string :encrypted_password, null: false, default: ""
## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      # t.integer  :sign_in_count, default: 0, null: false
      # t.datetime :current_sign_in_at
      # t.datetime :last_sign_in_at
      # t.string   :current_sign_in_ip
      # t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at
    t.timestamps null: false
    end

Change here!!
     - add_index :users, :email,      unique: true
     + add_index :users, :employee_number,      unique: true
      add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end
$ rails db:migrate

● Change controller

application_controller.rb


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

  #Override method.
  def configure_permitted_parameters
    sign_up_params = [:employee_number, :password, :password_confirmation]
    sign_in_params = [:employee_number, :password, :remember_me] 

      # account_update, sign_in, sign_up,Redefine the field of
    devise_parameter_sanitizer.permit(:sign_up, keys: sign_up_params)
    devise_parameter_sanitizer.permit(:sign_in, keys: sign_in_params)
    devise_parameter_sanitizer.permit(:account_update, keys: account_update)
  end
 end

This completes the settings. All you have to do is change the view and you're done.

reference

[* Rails *] How to use devise (rails5 version) Ruby on Rails beginners tried using gem Devise.

Recommended Posts

[Beginner] How to use devise Change settings from introduction
How to use JUnit (beginner)
[Rails] How to use gem "devise"
[Rails] How to use devise (Note)
From introduction to use of ActiveHash
[Introduction to Rails] How to use render
How to change from HTML to Haml
[Flutter] How to use C / C ++ from Dart?
[Note] How to use Rails 6 Devise + cancancan
How to use enum (introduction of Japanese notation)
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use collection_select
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
From the introduction of devise to the creation of the users table
[rails] How to use devise helper method before_action: authenticate_user!
[Beginner] Discover the N + 1 problem! How to use Bullet
How to change from Oracle Java 8 to Adopt Open JDK 9
[Java] How to use Map
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use Ruby return
[Rails] How to install devise
[Rails] How to use enum
[Swift] How to use UserDefaults
How to use java class
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use String [] args
[Java] How to use string.format
How to use rails join
How to use Java Map
Ruby: How to use cookies
How to use dependent :: destroy
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation
How to use Java variables
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
How to use GC Viewer