LoginSignup
8
7

More than 5 years have passed since last update.

Rails5でのdeviseの導入方法

Last updated at Posted at 2018-10-22

はじめに

初めてdeviseを使っての認証機能を実装したので、自分用の備忘録としてまとめておきます。

deviseとは

deviseとは、認証機能を簡単に実装できるgemです。
Railsチュートリアルで学習していた時は、この認証機能をいちから作っていって苦しめられたので、このgemを知った時はかなり感動しました。

導入方法

1.gemファイルの編集

source 'https://rubygems.org'
.
.
.
(省略)

gem 'devise'

gemの追加をしたので、忘れずにbundle installをしておきましょう。

$ bundle install

2.デバイスの設定

deviseの設定ファイルを以下のコマンドで、アプリケーションにインストールします。

$ 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

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

すると、deviseを使うために4つの指示がされるので、順番に設定していきます。


①デフォルURLの設定

  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.

指示されている通りに、

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

上記の部分のコードを、指定しされたconfig/environments/development.rbファイルに追加します。

config/environments/development.rb
Rails.application.configure do
  # Settings specified here will take precedence over those in 
.
.
.
(省略)
  config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end

②ルートURLの設定

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

       root to: "home#index"

上記のroot to: "home#index"は、あくまでも一例なので、任意でのルートURLで大丈夫です。

config/routes.rb
Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
 root 'users#index'
end

私は今回のアプリでは、Usersコントローラーのindexページを、ルートURLに設定します。


③フラッシュメセージの設定

  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>

指示されている通りに、

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>  

上記の部分のコードを、指定されたapp/views/layouts/application.html.erbファイルに追加します。

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
.
.
.
(省略)

  <body>
    <p class="notice"><%= notice %></p>
    <p class="alert"><%= alert %></p>  

    <%= yield %>
  </body>
</html>

④deviseのデフォルトのviewをカスタマイズできるように設定

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

       rails g devise:views

deviseがデフォルトで持っているviewはかなり味気のないデザインの為、自分でカスタマイズしたい方は指示されたコマンドを、ターミナに入力します。
デフォルのデザインで良いという方は飛ばして次に行ってください。

自分でカスタマイズしたい方は、上記のコマンドをターミナルに入力します。

$ rails g devise:views
      invoke  Devise::Generators::SharedViewsGenerator
      create    app/views/devise/shared
      create    app/views/devise/shared/_links.html.erb
      invoke  form_for
      create    app/views/devise/confirmations
      create    app/views/devise/confirmations/new.html.erb
      create    app/views/devise/passwords
      create    app/views/devise/passwords/edit.html.erb
      create    app/views/devise/passwords/new.html.erb
      create    app/views/devise/registrations
      create    app/views/devise/registrations/edit.html.erb
      create    app/views/devise/registrations/new.html.erb
      create    app/views/devise/sessions
      create    app/views/devise/sessions/new.html.erb
      create    app/views/devise/unlocks
      create    app/views/devise/unlocks/new.html.erb
      invoke  erb
      create    app/views/devise/mailer
      create    app/views/devise/mailer/confirmation_instructions.html.erb
      create    app/views/devise/mailer/email_changed.html.erb
      create    app/views/devise/mailer/password_change.html.erb
      create    app/views/devise/mailer/reset_password_instructions.html.erb

すると、たくさんのビューファイルが作成されます。

これでdeviseの設定は完了です。

3.deviseで認証する為のモデルを作る

デバイスの設定が完了したので、いよいよログインページを作っていきます。
下記のコマンドをターミナルに入力します。

$ rails g devise User

モデル名であるUserの部分は、作成したい任意のモデル名で大丈夫です。
今回は、Userモデルにしました。

上記のコマンドを入力すると、以下のファイルが作成されます。

      invoke  active_record
      create    db/migrate/20181022115215_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

この作成されたファイルを見てみると
Userモデルapp/models/user.rbやルートroute devise_for :users
が作成されているのがわかります。

モデルを作成したので、忘れずにマイグレーションを実行しておきましょう。

$ rails db:migrate

これで、ルートも作成されたので実際にログインページを開けるようになりました。
以下のコマンドで、ルートの一覧を見ることができます。

$ 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_password GET    /users/password/new(.:format)                                                            devise/passwords#new
       edit_user_password GET    /users/password/edit(.:format)                                                           devise/passwords#edit
            user_password PATCH  /users/password(.:format)                                                                devise/passwords#update
                          PUT    /users/password(.:format)                                                                devise/passwords#update
                          POST   /users/password(.:format)                                                                devise/passwords#create
 cancel_user_registration GET    /users/cancel(.:format)                                                                  devise/registrations#cancel
    new_user_registration GET    /users/sign_up(.:format)                                                                 devise/registrations#new
   edit_user_registration GET    /users/edit(.:format)                                                                    devise/registrations#edit
        user_registration PATCH  /users(.:format)                                                                         devise/registrations#update
                          PUT    /users(.:format)                                                                         devise/registrations#update
                          DELETE /users(.:format)                                                                         devise/registrations#destroy
                          POST   /users(.:format)                                                                         devise/registrations#create
       rails_service_blob GET    /rails/active_storage/blobs/:signed_id/*filename(.:format)                               active_storage/blobs#show
rails_blob_representation GET    /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
       rails_disk_service GET    /rails/active_storage/disk/:encoded_key/*filename(.:format)                              active_storage/disk#show
update_rails_disk_service PUT    /rails/active_storage/disk/:encoded_token(.:format)                                      active_storage/disk#update
     rails_direct_uploads POST   /rails/active_storage/direct_uploads(.:format)                                           active_storage/direct_uploads#create

http://localhost:3000/users/sign_inなどの追加されたURLを開いてみましょう。
ログインやログアウトなどのページが追加されたことが確認できます。


以上がdeviseの導入です。お疲れ様でした。

参考サイト

devise公式ページ
[Rails] deviseの使い方(rails5版)

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7