deviseのよく使うメソッド集
背景
よく使うgem「devise」は便利なメソッドがあるが、その度に調べるのは面倒なのでまとめておくこととした。
メソッド集
⑴configure_permitted_parameters メソッド,⑵devise_parameter_sanitizer メソッド
⑴deviseでは初期状態ではサインアップ時にメールアドレスとパスワードのみを受け取るように設定してあるので、追加したキーのパラメーターは許可されない。追加のパラメーターを許可したい場合は、application_controllerにおいてbefore_actionにconfigure_permitted_parametersメソッドを設定します。
[例]ユーザー名、年齢も一緒に登録したい等。
⑵deviseで設定されているstrong_parametersに対してパラメーターを追加することができます。
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
end
end
after_sign_out_path_for メソッド
deviseでサインアウト後、リダイレクト先を指定するメソッド。
このメソッドは返り値にサインアウト後のリダイレクト先URLを指定出来ます。
deiviseのメソッドを上書きしている関係上、resourceを引数に渡さなけらばならないので、resourceを引数に渡します。
(逆のサインイン後の指定をするときは、after_sign_in~とする)
def after_sign_out_path_for(resource)
user_path(resorces) # サインアウト後のリダイレクト先URL
end
def after_sign_in_path_for(resource)
users_path # サインイン後のリダイレクト先URL
end
authenticate_user! メソッド
コントローラーに設定して、ログイン済ユーザーのみにアクセスを許可するメソッド。
except:を指定することでそのアクションは対象外にできる。
before_action :authenticate_user!,except: [:index, :show]
user_signed_in? メソッド
ユーザーがサインイン済かどうかを判定する
[例]ログインしていない時に他のアクションが動かないようにする
before_action :move_to_index, except: :index
def index
end
private
def move_to_index
redirect_to action: :index unless user_signed_in?
end
current_user メソッド
サインインしているユーザーを取得する
user_session メソッド
ユーザーのセッション情報にアクセスする
class ArticlesController < ApplicationController
...
def index
user_session[:cart] = "Cart"
respond_with(current_user)
end
Author And Source
この問題について(deviseのよく使うメソッド集), 我々は、より多くの情報をここで見つけました https://qiita.com/ren0826jam/items/3a9e9cd61419253c2e65著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .