大田区から発信するゆるゆる日記

主にITエンジニアに関する備忘録日記。たまに趣味も。何か不備があればコメント頂けると幸いです。Twitterアカウント https://twitter.com/ryuzan03

【Rails】deviseのログイン後表示ページの変更

※下記の内容に不備がありましたら、コメント頂けると幸いです。また、下記の内容をご使用頂ける場合は自己責任でお願いします。

【目次】

 

メリット

deviseのログイン後の移動先ページをログイン前のページにリダイレクトできるようになる

 

背景

 ログイン後のページが全てUserページになるのは味気ないなと思い、調べてみました。 

 

内容

ログイン前のページを保存

app/controllers/application_controller.rb に以下を追記します。

class ApplicationController < ActionController::Base

before_action :store_user_location, unless: :devise_controller?
before_action :authenticate_user!

---------

private

def store_user_location
store_location_for(:user, request.fullpath)
end

end

 

ログイン後のリダイレクト先を変更

app/controllers/application_controller.rbを変更します。

 def after_sign_in_path_for(resource)
stored_user_for(resource) || root_path
end

 

今後に向けて

まだ解明途中なので、今日はここまで。

 

参考

【Rails5】devise でログイン後ページをユーザー意図に合わせて変更する - グロースエンジニアのブログ

How To: Redirect back to current page after sign in, sign out, sign up, update · plataformatec/devise Wiki · GitHub