[RUBY] [Rails] How to use devise (Note)

Introduction

Until now, I had implemented authentication functions such as login and logout by myself, but I would like to use devise when creating a portfolio this time, so I will leave this article as a memorandum of how to use it.

Execution environment

This article has been confirmed to work in the following environment. ruby 2.7.1 rails 6.0.3 devise 4.7.3

Installation

Added to Gemfile. I will translate it into Japanese in the second half, so I will include that gem as well.

Gemfile


gem 'devise'
gem 'devise-i18n'
gem 'devise-i18n-views'

Run bundle install.

$ bundle install

devise settings

Create related files.

$ rails g devise:install

Then the file will be created and the following English text will be displayed.

Running via Spring preloader in process 5911
      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 *

===============================================================================
  1. Define the default url option in the environment file.

config/environments/development.rb


config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
  1. Define the root url.

config/routes.rb


root to: 'homes#index'
  1. Write the following in the place where you want to display the flash.
<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>
  1. Customization of view will be described later.

Creating a User model

$ rails g devise User

Looking at the created migration file, there are only email and password, so add any columns you want to add. Execute migration after adding.

$ rails db:migrate

At this point, open http: // localhost: 3000 / users / sign_up and a new registration page will be created. If you forget to add a column and want to add it later, execute the following. (This time, we will assume the addition of the username column)

$ rails g migration add_username_to_users username:string

Be sure to enter the username, so put a NOT NULL constraint.

db/migrate/XXXXXXXXXXXXXX_add_username_to_users.rb


class AddUsernameToUsers < ActiveRecord::Migration[6.0]
  def change
    add_column :users, :username, :string, null: false
  end
end

Creating a view for devise

I want to customize the view, so execute the following.

$ rails g devise:views users

Reflects the edited contents of view.

config/initializers/devise.rb


#Config on line 247.scoped_views =Uncomment false and change to true
config.scoped_views = true

Allows usernames to be registered during sign_up.

app/controllers/application_controller.rb


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

  protected

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

Create a controller and change the routing

$ rails g devise:controllers users

The controller file and English text are displayed.

Running via Spring preloader in process 9004
      create  app/controllers/users/confirmations_controller.rb
      create  app/controllers/users/passwords_controller.rb
      create  app/controllers/users/registrations_controller.rb
      create  app/controllers/users/sessions_controller.rb
      create  app/controllers/users/unlocks_controller.rb
      create  app/controllers/users/omniauth_callbacks_controller.rb
===============================================================================

Some setup you must do manually if you haven't yet:

  Ensure you have overridden routes for generated controllers in your routes.rb.
  For example:

    Rails.application.routes.draw do
      devise_for :users, controllers: {
        sessions: 'users/sessions'
      }
    end

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

Now let's check the current routing.

$ rails routes

Prefix               Verb   URI Pattern                          Controller#Action
new_user_session     GET    /users/sign_in(.:format)             devise/sessions#new
user_session         POST   /users/sign_in(.:format)             devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format)            devise/sessions#destroy
...
new_user_registration GET    /users/sign_up(.:format)       devise/registrations#new

If the Controller # Action part is devise / registrations, devise / sessions like this, the method to be defined from now on will not be reflected.

Override the route according to the English text that was displayed when you created the controller.

config/routes.rb


devise_for :users, controllers: {
    registrations: 'users/registrations',
    sessions: 'users/sessions'
  }

Now that we have overridden it, check the current routing.

$ rails routes

Prefix               Verb   URI Pattern                    Controller#Action
new_user_session     GET    /users/sign_in(.:format)       users/sessions#new
user_session         POST   /users/sign_in(.:format)       users/sessions#create
destroy_user_session DELETE /users/sign_out(.:format)      users/sessions#destroy
...
new_user_registration GET    /users/sign_up(.:format)      users/registrations#new                   

This will allow you to customize your controller. Define the method.

app/controllers/users/registrations_controller.rb


  #Redirect destination after creating an account
  def after_sign_up_path_for(resource)
    root_path
  end

  #Redirect destination after editing the account
  def after_update_path_for(resource)
    root_path
  end

app/controllers/users/sessions_controller.rb


  #Redirect destination after logout
  def after_sign_out_path_for(resource)
    root_path
  end

  #Redirect destination after login
  def after_sign_in_path_for(resource)
    root_path
  end

Now all redirect destinations are on the top page.

Translate to Japanese

First, let's set the default language of this Rails application to Japanese.

config/application.rb


require_relative 'boot'
require 'rails/all'

Bundler.require(*Rails.groups)

module ConnectStudy
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0
  
    config.i18n.default_locale = :ja #Add here
  end
end

Generate a Japanese translation file for devise.

$ rails g devise:views:locale ja

This will be in Japanese. Don't forget to restart the server when you change the config.

devise also has a lot of useful helper methods, so I'd like to use them to develop apps efficiently.

Recommended Posts

[Rails] How to use devise (Note)
[Note] How to use Rails 6 Devise + cancancan
[Rails] How to use gem "devise"
[Rails] How to use enum
[Rails] How to install devise
[Rails] How to use enum
How to use rails join
[Rails] How to use validation
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
[Rails] How to use Scope
[Rails] How to use flash messages
[rails] How to use devise helper method before_action: authenticate_user!
How to use Ruby on Rails
[Rails] How to use Active Storage
[Introduction to Rails] How to use render
How to use custom helpers in rails
[Ruby on Rails] How to use CarrierWave
[Rails] How to use rails console with docker
[Rails] How to use ActiveRecord :: Bitemporal (BiTemporalDataModel)
[Rails] How to use the map method
How to use MySQL in Rails tutorial
How to use Java Scanner class (Note)
[Ruby on Rails] How to use redirect_to
[Ruby on Rails] How to use kaminari
[Rails] How to use video_tag to display videos
Ruby: CSV :: How to use Table Note
[Rails] How to use helper method, confimartion
How to use credentials.yml.enc introduced in Rails 5.2
[Rails] How to translate devise into Japanese
How to use Map
How to write Rails
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 map
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 uninstall Rails
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
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
[Rails] How to use select boxes in Ransack
How to use rails g scaffold, functions, precautions
Note how to use Swift super basic TableView
How to use Segmented Control and points to note
How to use JQuery in js.erb of Rails6
[Rails] How to use Gem'rails-i18n' for Japanese support