deviseのよく使うメソッド集


背景

よく使うgem「devise」は便利なメソッドがあるが、その度に調べるのは面倒なのでまとめておくこととした。

メソッド集

⑴configure_permitted_parameters メソッド,⑵devise_parameter_sanitizer メソッド

⑴deviseでは初期状態ではサインアップ時にメールアドレスとパスワードのみを受け取るように設定してあるので、追加したキーのパラメーターは許可されない。追加のパラメーターを許可したい場合は、application_controllerにおいてbefore_actionにconfigure_permitted_parametersメソッドを設定します。
[例]ユーザー名、年齢も一緒に登録したい等。

⑵deviseで設定されているstrong_parametersに対してパラメーターを追加することができます。

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: [:username])
  end
end
after_sign_out_path_for メソッド

deviseでサインアウト後、リダイレクト先を指定するメソッド。
このメソッドは返り値にサインアウト後のリダイレクト先URLを指定出来ます。
deiviseのメソッドを上書きしている関係上、resourceを引数に渡さなけらばならないので、resourceを引数に渡します。
(逆のサインイン後の指定をするときは、after_sign_in~とする)

application_controller.rb

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:を指定することでそのアクションは対象外にできる。

users_controller.rb

before_action :authenticate_user!,except: [:index, :show] 
user_signed_in? メソッド

ユーザーがサインイン済かどうかを判定する
[例]ログインしていない時に他のアクションが動かないようにする

tweets_controller.rb
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 メソッド

ユーザーのセッション情報にアクセスする

articles_controller.rb

class ArticlesController < ApplicationController
...
  def index
    user_session[:cart] = "Cart"
    respond_with(current_user)
  end