LoginSignup
2
3

More than 1 year has passed since last update.

deviseについて

Last updated at Posted at 2021-10-30

はじめに

RubyのライブラリであるGemの「devise」のまとめです。
「device」ではなくて「devise」なので注意。

deviseでできること

「devise」は簡単に認証機能を作成することができます。
認証機能は新規登録画面とかログイン画面とかのことで、
ユーザー登録が必要なサイトでは必須ですよね。

導入してみる

deviseのインストール

Gemfile
gem 'devise'

を追加して

$ bundle install

をターミナルに入力。

初期設定

設定ファイルをインストールするために

$ rails g devise:install

これでdeviseを使用する準備は完了。

config/initializers/devise.rb
config/locales/devise.en.yml

の設定ファイルが作成されているはずです。

テーブルの作成

今回はモデル名は「User」で作成します。
「devise」はユーザテーブルを自動的に作成してくれるので
「rails g model User」はしなくても大丈夫です。

$ rails g devise User

「User」モデルと、「users」のマイグレーションファイルが作成されます。

テーブルの編集

ログイン機能に必要な「email」と「passward」はデフォルトで管理してくれているので、
他にユーザー登録、ユーザーテーブルに必要なカラムを追加してあげます。

時間_devise_create_users.rb
t.string :name

今回必要なカラムは「name」のみなので、上記を入力。
他に姓と名を分けたり、電話番号や住所が登録に必要な場合はここで入力しておきます。
ここでちゃんと保存はしておきましょう。
入力を終えたら

$ rails db:migrate

をし、テーブルを作成します。
作成したら、

config/routes.rb
devise_for :users
app/models/user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
end

が追加されています。
一つ目は「devise」のURLには「users」が含まれるようになっているという表示。
二つ目の説明は今回省きます。とりあえず、deviseのデフォルトの機能です。

nameを登録できるようにする

今回は「name」をカラム追加しているため

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: [:name])
  end
end

before_action :configure_permitted_parameters, if: :devise_controller?は
「devise」の機能の前に「configure_permitted_parameters」をしてくださいという記述です。
その「configure_permitted_parameters」の中身が
新規登録時に名前(name)の操作を許可するという記述です。

ユーザー登録画面を編集

「devise」をインストールすると自動的にデフォルトのviewが用意されているので、利用可能ではあるのですが、今回は「name」を追加しているため、編集を行います。

$ rails g devise:views

をすると、色々と追加されますが、今回「name」を追加しているため
「name」の入力欄のみ追加します。

app/views/devise/registrations/new.html.erb
〜省略〜

<div class="field">
  <%= f.label :name %><br />
  <%= f.text_field :name, autofocus: true %>
</div>

〜省略〜

これで新規登録で名前を追加することができるようになりました。
あとは、このままだとログアウトできないので、任意のページにログアウトの記述をしてあげてください。

<% if user_signed_in? %>
  <%= link_to "ログアウト", destroy_user_session_path, method: :delete %>
<% end %>

<% if user_signed_in? %>はdeviseで使用できるヘルパーです。
ログイン済みであれば、、、の意味なので、ログイン済みの場合はログアウトの表示をするという記述です。

以上で実装終了とします。
まだまだアレンジ等できるみたいですので、自分用にカスタマイズできるようになれたらなと思います。

2
3
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
2
3