LoginSignup
63
68

More than 5 years have passed since last update.

超基本的なdeviseの使い方

Posted at

導入手順

  • gem 'devise'をGemfileに追記
  • bundle install でgemの読み込み
  • ローカルサーバーの再起動 rails s
  • deviseを使用する為にはインストールに加えてdevise専用のコマンドを利用して設定ファイルを作成する必要がある。 rails g devise:install
  • rails g devise user でログイン機能を持つUserクラスをもつモデルを作る。 その時にusersテーブルにカラムを追加するためのマイグレーションファイルができているので rake db:migrate を実行。するとusersテーブルが出来る。 ちなみにuserのモデル名は任意なので何でもok

deviseを使う事で利用できるメソッド

user_signed_in?

ユーザーがサインインしているかどうかを検証するメソッド。サインインしている場合にはtrueを返し、そうでない場合はfalseを返す。

ログインしている時とそうでない場合の使い方の例


      <% if user_signed_in? %>
        <div class="user_nav grid-6">
          <%= link_to "ログアウト", destroy_user_session_path, method: :delete %>
          <a class="post" href="/hoge/new">投稿する</a>
        </div>
      <% else %>
        <div class="grid-6">
          <%= link_to "ログイン", new_user_session_path, class: 'post' %>
          <%= link_to "新規登録", new_user_registration_path, class: 'post' %>
        </div>
      <% end %>

devise用のviewファイルを作成する

rails g devise:views
とコマンドを打つとapp/views/deviseのファイルに各種viewファイルが作成される

サインアップ画面のview
app/views/devise/ragistrations/new.html.erb

ログイン画面のview
app/views/devise/sessions/new.html.erb

deviseの各アクションへのパス

ターミナルでrake routesを実行して確認。

configure_permitted_parametersメソッド

deviseではサインアップ時にメールアドレスとパスワードのみを受け取るようにストロングパラメーターで設定してあるのでキーを追加しても許可されません。

そこで登場するのがconfigure_permitted_parametersメソッド

configureは設定する
permittedは許可
parametersはパラメーター
という意味。
単純にdeviseで利用出来るパラメーターを設定しますよ。という意味。

パラメーターに追加したい場合はapplication_controller
before_actionconfigure_permitted_parametersメソッドを設定する。


例
  class ApplicationController < ActionController::Base
    # Prevent CSRF attacks by raising an exception.
    # For APIs, you may want to use :null_session instead.
    protect_from_forgery with: :exception
    before_action :configure_permitted_parameters, if: :devise_controller?

    def configure_permitted_parameters
      devise_parameter_sanitizer.permit(:sign_up, keys: [:nickname])
    end
  end

63
68
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
63
68