Deviseでログイン後のURLを変える方法
移転しました →
RailsでDeviseを使っているときの話。いくらでも情報がある話ですが、自分のためにメモります。
http://hostname/ にログインボタンを置いておいて、ログイン後はhttp://hostname/memberとかに移動したいケースがあると思いますが、これは比較的簡単に書けます。
# application_controller.rb ApplicationController # ... def after_sign_in_path_for(resource) member_path # ログイン後に遷移したいパス end end
応用例
Deviseのドキュメントからの引用です。
after_sign_in_path_for
ログイン前のパスを覚えておいて、ログイン後にはそちらのURLに戻るという遷移を実現できます。
ありそうなシチュエーションとしては、FacebookとかでシェアされたコンテンツのURLを踏んだ人がサインアップしたらそのコンテンツのURLに飛ぶみたいな場合ですね。
次のようなコードで実現できるようです。要はリクエストのたびにフルパスの情報をセッションに残しておいて、ログイン後のURLは保存しておいた値を使うというものです。
# application_controller.rb after_filter :store_location def store_location # store last url - this is needed for post-login redirect to whatever the user last visited. if (request.fullpath != "/users/sign_in" && request.fullpath != "/users/sign_up" && request.fullpath != "/users/password" && !request.xhr?) # don't store ajax calls session[:previous_url] = request.fullpath end end def after_sign_in_path_for(resource) session[:previous_url] || root_path end