[Rails] How to log in with a name by adding a devise name column


I was addicted to it when I started using devise, so I will leave it in the article.



The overall flow is as follows.

** 1. Add name column 2. Change the settings of devise.rb 3. Edit the controller 4. Edit View **

1. Add a name column

Create a new migration file. To add the name column to the User model, execute the command as shown below.


$ rails g migration add_name_to_users name:string

It is OK when the following screen is displayed.


    invoke  active_record
    create    db/migrate/20201104152112_add_name_to_users.rb

When you check the migration file, it is described as follows.


class AddNameToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :name, :string

Execute migration to reflect it in the DB.


$ rails db:migrate

It is OK if the following is displayed.


== 20201104152112 AddNameToUsers: migrating ==================================
-- add_column(:users, :name, :string)
   -> 0.0042s
== 20201104152112 AddNameToUsers: migrated (0.0043s) =========================

The name column is now added to the User model and reflected in the DB.

2. Change the settings of devise.rb

In order to log in with name instead of email, you need to change the settings in devise.rb. (I was addicted to it before because I hadn't made this change. Don't forget to do it!)

in app/config/initializers/devise.rb ** config.authentication_keys = [: email] ** Uncomment Change ** config.authentication_keys = [: name] **.


#Searching for the relevant part with ⌘F is quick.

  # ==> Configuration for any authentication mechanism
  # Configure which keys are used when authenticating a user. The default is
  # just :email. You can configure it to use [:username, :subdomain], so for
  # authenticating a user, both parameters are required. Remember that those
  # parameters are used only when authenticating and not when retrieving from
  # session. If you need permissions, you should implement that in a before filter.
  # You can also supply a hash where the value is a boolean determining whether
  # or not authentication should be aborted when the value is not present.

  # config.authentication_keys = [:email]Change this line as below
    config.authentication_keys = [:name]

You have now changed your settings to authenticate with name instead of email.

3. Edit the controller

Then edit application_controller.rb.


class ApplicationController < ActionController::Base
  before_action :configure_permitted_parameters, if: :devise_controller?


  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name])

before_action :configure_permitted_parameters, if: :devise_controller? To briefly explain this, the first thing to do when using devise is to run the configure_permitted_parameters method. The method is defined below it.

devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) This indicates that you are allowed to send the value of name when you sign up. Email and password values ​​are allowed by default.

In other words, it's okay if you think that the value of name is made available by the configure_permitted_parameters method when the devise process is executed.

(If you are wondering what protected is, you can be happy by searching for "rails strong parameters" etc.)

4. Edit View

You can create a devise-related view with the following command.


$ rails g devise:views


      invoke  Devise::Generators::SharedViewsGenerator
      create    app/views/devise/shared
      create    app/views/devise/shared/_error_messages.html.erb
      create    app/views/devise/shared/_links.html.erb
      invoke  form_for
      create    app/views/devise/confirmations
      create    app/views/devise/confirmations/new.html.erb
      create    app/views/devise/passwords
      create    app/views/devise/passwords/edit.html.erb
      create    app/views/devise/passwords/new.html.erb
      create    app/views/devise/registrations
      create    app/views/devise/registrations/edit.html.erb
      create    app/views/devise/registrations/new.html.erb
      create    app/views/devise/sessions
      create    app/views/devise/sessions/new.html.erb
      create    app/views/devise/unlocks
      create    app/views/devise/unlocks/new.html.erb
      invoke  erb
      create    app/views/devise/mailer
      create    app/views/devise/mailer/confirmation_instructions.html.erb
      create    app/views/devise/mailer/email_changed.html.erb
      create    app/views/devise/mailer/password_change.html.erb
      create    app/views/devise/mailer/reset_password_instructions.html.erb
      create    app/views/devise/mailer/unlock_instructions.html.erb

The view creation is complete.

There are two tasks from here.

-** Edit the sign-up screen so that you can register your name. ** ** -** Edit the login screen so that you can log in with name. ** **

I will look at them in order.

First, the view on the sign-up screen will be new.html.erb in app/views/devise/registrations, so edit it.


<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= render "devise/shared/error_messages", resource: resource %>

  <%#add to%>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true, autocomplete: "name" %>
  <%#So far%>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>


Start the server and go to/users/sign_up. signup_name.png

You now have a space to enter your name on the sign-up screen.

Next, the view of the login screen will be new.html.erb in app/views/users/sessions, so let's edit this so that you can log in with name.


<h2>Log in</h2>

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
  <div class="field">

    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
    <%#So far%>

    <%#add to%>
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true, autocomplete: "name" %>
    <%#So far%>



Try accessing/users/sign_in. login_name.png

You can now log in by name.


This article was written with reference to the following information.

User Login Guide Using devise Function & Login by Name Beginners customize devise so that they can register and log in with just name and password in devise! ~ Thorough and slow commentary ~ About editing before_action and strong parameters

Recommended Posts

[Rails] How to log in with a name by adding a devise name column
[How to insert a video in haml with Rails]
[Rails] Processing after adding a column to the devise table
How to change app name in rails
How to insert a video in Rails
How to rename a model with foreign key constraints in Rails
How to implement a slideshow using slick in Rails (one by one & multiple by one)
How to update user edits in Rails Devise without entering a password
How to separate .scss by controller in Rails
[Rails] How to get the user information currently logged in with devise
How to implement a like feature in Rails
How to easily create a pull-down in Rails
How to make a follow function in Rails
How to reference a column when overriding the column name method in ActiveRecord
[Rails6] How to connect the posting function generated by Scaffold with the user function generated by devise
How to store data simultaneously in a model associated with a nested form (Rails 6.0.0)
[Rails] How to search by multiple values ​​with LIKE
How to implement a like feature in Ajax in Rails
How to delete a new_record object built with Rails
[Ruby on Rails] How to change the column name
How to manually generate a JWT with Rails Knock
[Rails] How to change the column name of the table
How to write a date comparison search in Rails
How to query Array in jsonb with Rails + postgres
[Rails 6] How to set a background image in Rails [CSS]
[Rails] How to load JavaScript in a specific view
How to get started with creating a Rails app
[Rails] How to install devise
[Rails] Add column to devise
How to deal with errors in Rails s could not find a JavaScript runtime.
[Rails] How to delete images uploaded by carrierwave (using devise)
How to select a specified date by code in FSCalendar
How to display a graph in Ruby on Rails (LazyHighChart)
Mapping to a class with a value object in How to MyBatis
Super easy in 2 steps! How to install devise! !! (rails 5 version)
How to set up a proxy with authentication in Feign
[Rails] How to use gem "devise"
[Rails] How to use devise (Note)
[Rails] How to write in Japanese
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
How to introduce jQuery in Rails 6
How to name variables in Java
How to get along with Rails
How to install Swiper in Rails
How to make a jar file with no dependencies in Maven
How to run a job with docker login in AWS batch
How to get boolean value with jQuery in rails simple form
How to implement search functionality in Rails
How to use custom helpers in rails
[Rails] How to use rails console with docker
How to use MySQL in Rails tutorial
Steps to set a favicon in Rails
[rails] How to configure routing in resources
[rails] How to create a partial template
How to handle sign-in errors with devise
How to implement ranking functionality in Rails
[Note] How to use Rails 6 Devise + cancancan
How to publish a library in jCenter
How to use credentials.yml.enc introduced in Rails 5.2
[Rails] How to translate devise into Japanese
How to build Rails 6 environment with Docker