Pythonとサラリーマンと

2020年6月にPythonを始めたサラリーマンのブログです。

Rails5でDeviseをデフォルト設定でインストールする。

環境

MacOS 10.14.5
Ruby 2.5.0
Rails 5.2.3

手順

1. Gemファイルの編集・bundle install

Gemファイルに以下の行を追記。

gem 'devise'

DeviseのGemをインストール。

$ bundle install

2. Deviseをインストール

$ rails g devise:install

3. 各種設定の調整

Deviseから各種設定を調整しておくように促されるので、1~4まで実施する。 Deviseからのメッセージは以下。

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

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

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

(1) まずはconfig/environments/development.rbに以下を追記。

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

(2) rootを追記するように言われるが、ここは無視。後でまとめてルーティングを修正する。

(3) Deviseではflashメッセージを使用しているので、app/views/layouts/application.html.erb.にflashを表示するよう追記する。

  <body>
    <p class="notice"><%= notice %></p> #追記する行
    <p class="alert"><%= alert %></p> #追記する行
    <%= yield %>
  </body>

(4) Deviseで作成されたページを編集できるようにViewをインストールする。

$ rails g devise:views

これでapp/views配下にapp/views/deviseディレクトリが作成され、各種erbファイルが含まれている。 各種ファイルが担うページは以下の通り。

app/views/devise/shared/_links.html.erb (リンク用パーシャル)
app/views/devise/confirmations/new.html.erb (認証メールの再送信画面)
app/views/devise/passwords/edit.html.erb (パスワード変更画面)
app/views/devise/passwords/new.html.erb (パスワードを忘れた際、メールを送る画面)
app/views/devise/registrations/edit.html.erb (ユーザー情報変更画面)
app/views/devise/registrations/new.html.erb (ユーザー登録画面)
app/views/devise/sessions/new.html.erb (ログイン画面)
app/views/devise/unlocks/new.html.erb (ロック解除メール再送信画面)
app/views/devise/mailer/confirmation_instructions.html.erb (メール用アカウント認証文)
app/views/devise/mailer/password_change.html.erb (メール用パスワード変更完了文)
app/views/devise/mailer/reset_password_instructions.html.erb (メール用パスワードリセット文)
app/views/devise/mailer/unlock_instructions.html.erb (メール用ロック解除文)

4. Userモデルを作成

以下を実行。

rails g devise User

今回はデフォルトの設定のままmigrationを行う。

rails db:migrate

なお、デフォルトのmigrationファイルは以下の通り。

class DeviseCreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              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.inet     :current_sign_in_ip
      # t.inet     :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

    add_index :users, :email,                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

5. usersコントローラファイルの作成

カスタムしたルーティングを使用するために、usersコントローラの各種ファイルを作成する。

$ rails g devise:controllers users

6. ルーティングを編集

Deviseをインストールした段階でデフォルトのルーティングは定義されている。 ユーザに分かりやすいパスに変更するために、config/routes.rbを以下に修正する。 なお、rootはログインページを指定。

Rails.application.routes.draw do

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

devise_scope :user do
  root :to => "devise/sessions#new"
  get "user/:id", :to => "users/registrations#detail"
  get "signup", :to => "users/registrations#new"
  get "login", :to => "users/sessions#new"
  get "logout", :to => "users/sessions#destroy"
  get "forgot", :to => "users/passwords#new"
end
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

7. ログイン強制と、ログイン後・ログアウト後のリダイレクト先の指定

app/users/application_controller.erbを以下の通り修正する。

class ApplicationController < ActionController::Base
  before_action :authenticate_user!

  def after_sign_in_path_for(resource)
    ログイン後_path # ログイン後に遷移するpathを設定
  end

  def after_sign_out_path_for(resource)
    new_user_session_path # ログアウト後に遷移するpathを設定
  end

end

とりあえず、以上な感じ。 オプション機能の利用方法など、学習する必要あり。