Handle devise with Rails

First of all, I would like to review the flow of device introduction (what I did) and let me remember it here. Since I am a beginner, please contact me each time if you tell me something wrong.

About devise

First, an overview of the device, this is a gem for implementing user management functionality. You can easily implement new registration and login / logout.

Introducing devise

Let's edit the Gemfile

gem 'devise'(Let's add to the last line)

You can now work with your device locally, in test, and in production.

Reboot the local server

After installing Gem, restart the local server running in the terminal once. This is because the timing of reflecting the installed Gem is when the server starts.

Create devise config file

In order to use devise, in addition to installing Gem, it is necessary to create a configuration file with a command dedicated to devise. Let's create a file with this command

% rails g devise:install

Success when the following log flows!

      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

Depending on your application's configuration some manual setup may be required:

  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', port: 3000 }

     In production, :host should be set to the actual host of your application.

     * Required for all applications. *

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"
     
     * Not required for API-only Applications *

  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>

     * Not required for API-only Applications *

  4. You can copy Devise views (for customization) to your app by running:

       rails g devise:views
       
     * Not required *

===============================================================================

Create User model on device

When using devise, it is necessary to create a new User model for creating an account. To create it, create a User model with devise's model creation command instead of the usual model creation method. You can generate the model, its accompanying migration file, and routing settings all at once with the following command. The paths related to devise are added to routes.rb.

 rails g devise user

Success in the following log

  invoke  active_record
      create    db/migrate/20200309082300_devise_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      insert    app/models/user.rb
       route  devise_for :users

In addition, the following routes are automatically added to routes.rb.

Rails.application.routes.draw do
  devise_for :users
  root to: 'tweets#index'
  resources :tweets
end

devise_for is a devise method that generates multiple routes required for user functions at once.

Creating a table

Since the migration file was also generated by the previous command, migrate it.

rails db:migrate

The table has been created here.

** Since the information in the table has been changed (migrated), let's restart the local server when starting it. ** **

Creating a view file for device

When you implement the login function in devise, the login / sign-up screen is automatically generated, but it is not generated as a view file. This is because we are loading a view file that exists inside the devise Gem.

In order to make changes to the devise view file, you need to use the devise command to generate the view file.

Run the command to create a view for devise

% rails g devise:views

Edit the view of the login screen and the view file of the new registration screen created here to create the appearance.

This completes the basic installation of device. I'm aware that if it's simple, it's okay here, but Also used in devise

rails g devise:contoroller users

There is. I would like to summarize how to use it in another article below. (Because I don't understand the required standards)

Installation of strong parameters

The information you enter when signing up is sent to the server as a parameter. For normal requests without devise, we wrote strong parameters in the controller to limit the parameters that could be received.

For devise, write strong parameters in the controller as well. However, the controller that handles devise is described in the Gem, so it cannot be edited. Also, if you implement the login function with devise, in addition to params, you will also receive parameters that are different from params.

From the above, we need a method to reflect strong parameters in the devise controller and a method to acquire devise-specific parameters.

devise_parameter_sanitizer method

Methods like params in devise. Parameters can be obtained from requests such as "login" and "new registration" related to devise's User model.

By combining this method with the permit method, you can also specify and include newly added columns for the strong parameters defined in devise.

The devise_parameter_sanitizer method is used in the newly defined private method like the previous strong parameters. Since the provider of devise introduces the newly defined method name as configure_permitted_parameters, it is customary to define it with this method name.

private
def configure_permitted_parameters  #Method names are customary
  #Allow parameters for devise User model
  devise_parameter_sanitizer.permit(:devise process name, keys: [:Keys to allow])
end

devise permit adds parameters to allow by specifying the key in the array for the key of devise processing name in the first argument and keys in the second argument.

For the process name of the first argument, sign_in, sign_up, account_update that have already been set in devise can be used, and they correspond to the processes at the time of sign-in, sign-up, and account information update, respectively.

Process name role
:sign_in When signing in (login)
:sign_up When performing sign-up (new registration) processing
:account_update When processing account information update

Write these descriptions in ** application_controller.rb **.

app/controllers/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: [:nickname])
  end
end

Notice that we are using an option called if in before_action. By specifying the method name in the value, it is set to execute the process only when the return value is true.

This time, I specified the helper method name of devise: devise_controller?, And if it is the processing of the controller related to devise, it is set to execute the configure_permitted_parameters method only at that time. Even if the process is read by other tweets controller etc., it is not executed.

About other commands

rails g migration command

A command to generate a migration. The migration was previously generated with the model with the rails g model command, but it is used when changing the contents of an already created table.

This command automatically describes what kind of table operation to perform according to the name of the specified file.

rails g migration Add Column name To Add destination table name By setting the column name to be added: type, migration is generated with the code required to add a column to the table written.

** Snake case and camel case **

The snake case and camel case each represent how to separate words.

Snake cases represent word breaks with underscores Camelcase capitalizes word breaks When words of variable name or function name are consecutive, there are several ways to separate the words. See the table below.

Notation method Explanation example
Camelcase adminUserCommentCreator with lowercase letters and uppercase word delimiters
Upper camel case One of the camel cases. AdminUserCommentCreator that capitalizes word delimiters from the beginning
Snake case Underscore word break admin_user_comment_creator

As a customary naming convention for Rails, use it properly as follows.

Target of naming Customary naming conventions
Class name upper camel case
Method name snake case
Variable name snake case

Observe these naming conventions when creating your own classes and methods.

Recommended Posts

Handle devise with Rails
[Rails] devise
Create My Page with Rails devise
[Rails] Introducing devise
rails + devise + devise_token_auth
How to handle sign-in errors with devise
[Rails] devise helper method
[Rails] Customize devise validation
Rails deploy with Docker
[Rails 6] RuntimeError with $ rails s
Handle files with NIO.2.
Handle JSON with minimal-json
[Rails] Learning with Rails tutorial
[Rails] Test with RSpec
[Rails] Development with MySQL
[Rails] devise introduction method
Supports multilingualization with Rails!
[rails] About devise defaults
Double polymorphic with Rails
I want to authenticate users to Rails with Devise + OmniAuth
[Rails] Initial setting of user-created login with devise, devise_token_auth
[Rails] Introduction of devise Basics
Introduced graph function with rails
[Rails] Express polymorphic with graphql-ruby
What is Rails gem devise?
[Rails] Upload videos with Rails (ActiveStorage)
Try using view_component with rails
[Rails] gem devise installation flow
[Vue Rails] "Hello Vue!" Displayed with Vue + Rails
[Rails] How to install devise
Japaneseize using i18n with Rails
API creation with Rails + GraphQL
Preparation for developing with Rails
(For beginners) [Rails] Install Devise
Run Rails whenever with docker
[Docker] Rails 5.2 environment construction with docker
Use multiple databases with Rails 6.0
[Rails] Add column to devise
[Rails] Specify format with link_to
Login function implementation with rails
[rails] error during devise installation
[Docker] Use whenever with Docker + Rails
Memorandum [Rails] User authentication Devise
Edit user information with Devise
Handle dates with Javascript (moment.js)
I was addicted to setting default_url_options with Rails devise introduction
[rails] Problems that cannot be registered / logged in with devise
[Rails] How to use gem "devise"
Rails + MySQL environment construction with Docker
[Rails] Push transmission with LINE Bot
[Rails] Make pagination compatible with Ajax
[rails] Login screen implementation in devise
[Rails] Unexpected validation error in devise
Implemented mail sending function with rails
[Rails] Creating a new project with rails new
Minimal Rails with reduced file generation
Create pagination function with Rails Kaminari
Build environment with vue.js + rails + docker
Eliminate Rails FatModel with value object
Recognize Rails projects with Intellij idea
[Grover] Generate PDF with Rails [2020 version]