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