Deviseの設定手順(Rails)


はじめに

アプリを作成するにあたって、Deviseをインストールしたのでその手順をメモします。

Deviseとは

認証機能を簡単に実装できるgemです。
railsチュートリアルではイチから作成していたことを考えると、Deviseは手間や安全性の面からかなり使い勝手はよさそうです。
しかし公式ドキュメントにも記載あるように、Deviseを理解するためにはrailsチュートリアル等を利用してシンプルな認証機能の仕組みを理解する必要があります。

バージョン

ruby   : 2.5.1
rails  : 5.2.2
device : 4.6.1

手順

rails newは完了したところから始めます。

gemのインストール

Gemfile
gem 'devise'

Gemfileに追加したらbundle installをします。

初期設定

次に以下のコマンドを実行すると以下のメッセージが渡されますので、ひとつひとつ対応します。

$ rails generate devise:install
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

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.デフォルトURLの設定

Ensure you have defined default url options in your environments files.
指示に従い、config/environments/development.rbに以下を追加します。

config/environments/development.rb
Rails.application.configure do
  # 省略
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end
2.ルートURLの設定

Ensure you have defined root_url to something in your config/routes.rb.
先に適当なコントローラを作成したうえで、ルートURLを設定します。

$ rails g controller home index show
routes.rb
Rails.application.routes.draw do
  root to: 'home#index'
  get 'home/show'
end
3.flashメッセージの設定

Ensure you have flash messages in app/views/layouts/application.html.erb.
こちらも指示に従って以下のようにします。

app/views/layouts/application.html.erb
# 省略
  <body>
    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>
    <%= yield %>
  </body>
# 省略
4.Device用のViewファイルを生成

You can copy Devise views (for customization) to your app by running
認証周りの基本viewはgem内にあるので以下コマンドで生成まとめて生成します。

$ rails g devise:views

Userモデルの作成

モデルを作成するとマイグレーションファイルが生成されるためmigrateします。

$ rails g devise User
$ rails db:migrate

rails sで確認

http://localhost:3000/users/sign_upで以下のようにブラウザが開けばとりあえず最初の設定は終了です。

参考サイト

[Rails] deviseの使い方(rails5版)