LoginSignup
6
12

More than 3 years have passed since last update.

Railsプロジェクトにdeviseを使ってログイン機能を導入する

Last updated at Posted at 2018-05-21

はじめに

Railsで作ったサービスに簡単にログイン認証機能を導入できるdeviseの使い方を簡単に解説します。(説明とかいいからログイン認証機能さっさと導入したいという方のお役にも立てると思います。)

deviseとは

deviseはRailsで作ったアプリに簡単にログイン認証機能を導入できるgemです。
(ログインしていない人にはこのページみせない、、とかログイン何回かミスったらアカウントをロックしたりとかの機能導入できます。)

deviseを導入する

まずRailsプロジェクトを作成していきます。

$ rails new devise-sample-app
$ cd devise-sample-app

Gemfileに以下を記述してインストールします。

Gemfile
# devise
gem 'devise'
terminal
$ bundle install

次に下記コマンドを実行します。

terminal
$ rails g devise:install

するとdeviseのセットアップ方法が表示されます。

terminal

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の指定を行ってください。
  2. route.rbでrootのURLの設定をしてください。
  3. エラーメッセージを表示するHTMLをapplication.html.erbに追加してください。
  4. deviseで生成されるデフォルトのログイン画面などをカスタマイズしたい場合、下記のコマンドを実行してください。

のような意味ですが今ここでは設定しなくて大丈夫です。

次に下記コマンドを実行します。

terminal
$ rails g devise User

上記コマンド実行後に

terminal
$ rails db:migrate

で、「localhost:3000/users/sign_up」にアクセスすると会員登録画面ができています。

スクリーンショット 2018-05-22 5.45.14.png

ログイン認証を設定する

これでログイン機能ができたので、次はログインが必要なページとログインなしで閲覧できるページを作成します。

terminal
$ rails g controller home index mypage

上記コマンドでhomeコントローラーとログインが必要なmypage、ログイン不要なindexを作成します。

次にhome_controller.rbにbefore_actionを追記します。
スクリーンショット 2018-05-22 5.56.16.png

これでmypageにアクセスするとログインを要求され、indexにアクセスするとそのまま閲覧できるかと思います。

6
12
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
6
12