LoginSignup
0
0

More than 3 years have passed since last update.

[Rails]deviseで使えるヘルパーメソッド一覧

Posted at

はじめに

個人でRailsアプリケーションを作った際にdeviseを使ったので備忘録として残しておきます。

deviseのヘルパーメソッドの種類

※下記のuserの部分はモデル名なので例えばpostがモデル名の場合はpostに置き換えてください

ヘルパーメソッド 説明
current_user 現在ログインしているユーザのレコードを取得する
user_signed_in? ユーザーがサインインしていればtrue、サインアウトしていればfalseが返ってくる
user_session ユーザーのsession情報にアクセスする
configure_permitted_parameters モデルにストロングパラメーターを追加します。デフォルトはメールアドレスとパスワードのみ適応されています。
authenticate_user! ログインしていないユーザーをログインページにリダイレクトさせます。before_action :authenticate_user! のように使います。 

補足

authenticate_user!
onlyexceptionでアクションを設定することが多い、例を以下に示す。

before_action :authenticate_user! , only: [:show, :edit, :update, :destroy]
 or
before_action :authenticate_user! , except: [:show, :edit, :update, :destroy]

configure_permitted_parameters
第一引数は下記のように指定できる
・sign_up: 新規登録時
・sign_in: ログイン時
・account_update: 更新時

下記に使用例を示します。

before_action :configure_permitted_parameters, if: :devise_controller?

def configure_permitted_parameters
   # サインアップ時にusernameのストロングパラメータを追加
   devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :image])
   # アカウント編集の時にnameとprofileのストロングパラメータを追加
   devise_parameter_sanitizer.permit(:account_update, keys:[:username,:image,:profile])
end
0
0
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
0
0