[RUBY] [Rails] Give this article to you who looked up in "devise name login"

Give this article to you who looked up in "devise name login"

Introduction

My name is yuki. Thanks to DMMWEBCAMP, I am now a WEB engineer, gathering my friends to develop services, tutoring programming, and enjoying my engineer life every day.

I'm sure you came to find out how to log in with your name and password using the Rails gem, Devise, with "devise name login".

For you, today I will explain the most understandable related articles as much as possible, and even the part "Why do it" so that it will be beneficial to you.

Please do your best until the end if you like.

Because you are me in the past ...

Target audience of the article

--For those who want to know how to log in using devise --Rails environment construction is completed, and those who have experience of implementing login with mail and password with devise

How to fix

Now let's talk about how and why. Please be careful not to overlook it in order. In addition, logging in with your name and password is hereinafter referred to as "name login".

Install Devise and do the initial setup

First, let's set devise as a major premise.

Add devise to Gemfile and install

: white_check_mark: Write the following at the bottom of the Gemfile

gem 'devise'

Run: white_check_mark: bundle install. You can now work with devise in your project.

devise initial settings

After bundle install is finished, we will set up devise.

: white_check_mark: Run rails g devise: install on the command line (where you run commands, such as a terminal).

This initial setup is required to create a ** device configuration file **. If you make this, you will be able to make the necessary settings for name login later.

Create the User table needed to log in

Next, create a table to store the user data needed for name login in the first place.

: white_check_mark: Run rails g devise User on the command line.

This is a little different from rails g model User, and it creates User's model and migration file through the function of devise. The reason for doing that is that it automatically creates the necessary columns (where you put information such as email).

Create a User model Add a name column to the migration file

If you execute the above command, you will find a migration file in db / migrate /. If you do rails db: migrate, you can create the minimum User table required to log in with the devise function, but this time we want to enable" name login ", so we will add a name column. .. The reason is simple: the place to put the user's name doesn't exist by default.

Please add it like this.

db/migrate/2020......devise_create_users.rb


#Omission
      ## 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.string :name #I added it here! !! !! !! !! !! !!
      t.timestamps null: false
#Omission

: white_check_mark: Add the above code and execute rails db: migrate

You have now created a User table with a name column.

Visualize the view file required so that the name can be registered at the time of new registration

Now that we are ready to save, we will be able to send the name information on the new registration screen. However, in the current state, ** I cannot edit the screen used for new registration or login of devise **. Because you can't see the file.

To be able to actually edit : white_check_mark: Execute the following command on the command line.

rails rails g devise:views

Now, a set of devise folders is created under app / views, and you can rewrite the new registration and login screen of devise.

Which is the most important file?

--Registration is new.html.erb in registrations --Login is new.html.erb in sessions

is.

Add a form to give a name to the new registration screen

Currently, only email can be sent from the new registration screen.

: white_check_mark: Let's edit this a bit so that we can send the name information.

app/views/users/registrations/new.html.erb


<h2>Sign up</h2>

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

<!--Add from here--!>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true, autocomplete: "name" %>
  </div>
<!--Add up to here--!>

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

  <--!Below this is omitted!-->

If you can do this

Run: white_check_mark: rails s to access localhost: 3000 / users / sign_up. It's okay if you have a name form.

However ...

Allow name information to be sent at the time of new registration

When you follow the steps above, the new registration will probably succeed and the Rails initial screen will appear, but you should see these disturbing characters on the command line.

Unpermittted parameter: :name

This is because the value: name is not allowed to be sent. is what it means. If you're reading this article, you've probably heard the term "strong parameters," and that's exactly what it is.

By default, you are not allowed to give the value of: name, so let's allow this.

: white_check_mark: Edit app / controllers / application_controller.rb. Please add as follows.

app/controllers/application_controller.rb


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

  private

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

You can think of this file as a controller for the entire application. What you write here will be applied when you execute the processing of the application.

before_action: configure_permitted_parameters, if:: devise_controller? Means "if you want to process devise, do something called configure_permitted_parameters ".

So what is configure_permitted_parameters? The methods defined under it. It's called devise_parameter_sanitizer.permit (: sign_up, keys: [: name]).

To explain this in an easy-to-understand manner, it means "deviseu, allow sending the value: name when sign_up! But do not allow other invalid values!".

: white_check_mark: After setting the above, try new registration again. You should no longer see the error message on the command line.

You can't log out! You can do this by deleting the cookie. For MAC, try pressing the "i" button next to the URL.

Change the form to send email on the login screen to the form to send name

: white_check_mark: Now that you can register your name from the new registration screen, let's modify the login screen as well.

app/views/users/sessions/new.html.erb


<h2>Log in</h2>

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

<!--Add from here--!>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true, autocomplete: "name" %>
  </div>
<!--Add up to here--!>

<!--Delete from here--!>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>
<!--Deleted so far--!>

  <--!Below this is omitted!-->

Removed the form for email and added the form for name.

: white_check_mark: Now let's log in with the name and password you registered earlier.

−−− −− − Yes, I can't. It's annoying. Looking at the command line, I see ʻUnpermitted parameters:: name` again. Let's fix this.

Change the value used for login from email to name

This time, it is actually different if something should be registered in application_controller as in the case of new registration. To fix the factors that are played here this time, you need to go to the file that has devise settings.

please remember. It's the file you created when you did rails g devise: install.

: white_check_mark: Now open config / initializers / devise.rb.

If you are using VSCcode, you can search by file name by pressing cmd (ctrl) + p.

A file with various settings such as Ujauja will open, but it's okay. I can search for a string with cmd + f, but try typing in config.au.

You should find the statement # config.authentication_keys = [: email]. devise has set the key for authentication here (that is, authentication, think of it as the value used for login), so uncomment here and change email to name. Let's do it.

It means # config.authentication_keys = [: name].

Now let's see if we can log in! I'm sure you can succeed without any errors.

Summary

--Let's install and configure devise properly --Add the name column to user's migration file --Let's allow the value of name to be sent at the time of new registration --Set devise so that you can log in using your name when you log in (so that you can be officially authenticated).

It's like that.

When you continue to study, please think carefully about "Why does writing the description work as you want?"

I support you. If you have any problems, DM I'll be waiting for you ~.

Introducing that I am also writing such an article

[Alumni] What I want to tell people who are thinking of attending DMM WEB CAMP

company introduction

I am currently working for a logistics x IT company called Dialog Co., Ltd.. As of September 2020, we are not recruiting engineers, but we are looking for various other occupations, so please visit the Wantedly page. Please look. I would be happy if someday someone would apply for my Qiita opportunity.

Interview article (impressions after joining the company)

Recommended Posts

[Rails] Give this article to you who looked up in "devise name login"
[rails devise] How to transition users who are not logged in to the login page
[Rails] Function restrictions in devise (login / logout)
How to change app name in rails
[Rails] How to log in with a name by adding a devise name column
[Rails] Added in devise: username not added to database
How to implement guest login in 5 minutes in rails portfolio
Introduce devise in Rails to implement user management functionality
[Rails Tutorial Chapter 2] What to do when you make a mistake in the column name
Memo that transitions to the login screen if you are not logged in with devise
To you who suffer from unexpected decimal points in Java
Implement login function in Rails simply by name and password (1)
Implement login function in Rails simply by name and password (2)
Super easy in 2 steps! How to install devise! !! (rails 5 version)
Implement login function simply with name and password in Rails (3)
[Organization] To you who get messed up with render & redirect_to