ruby on rails - Redirect to previous page wherever it is directed to the login page -
i'm using rails 3.2 , authlogic. have following code:
class applicationcontroller < actioncontroller::base private def store_location session[:return_to] = request.url end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end end class usersessionscontroller < applicationcontroller before_filter :require_no_user, :only => [:new, :create] before_filter :require_user, :only => :destroy def new @user_session = usersession.new @header_title = "login" end def create @user_session = usersession.new(params[:user_session]) if @user_session.save flash[:success] = "login successful!" redirect_back_or_default root_url else render 'new' end end def destroy current_user_session.destroy flash[:success] = "logout successful!" redirect_back_or_default root_url end end
this code quite generic. when use before_filter
:
before_filter :require_user, :only => [:new, :edit, :update, :create]
it automatically store_location
, redirect proper page. however, how do this:
- i'm in
posts/1
doesn'trequire_user
. - i click login link on top navigation bar.
- it shows login page.
- once login, redirected
posts/1
instead ofroot_url
.
place direct call store_location
in sessions controller new
action.
# user_sessions_controller.rb def new store_location if session[:return_to].blank? @user_session = usersession.new @header_title = "login" end
this first check existing return_to
pair in sessions hash. don't want overwrite in case, example, user redirected new
action because of bad password.
this skip store_location
if called require_user
.
after successful redirect, have delete return_to
pair sessions hash; setting nil not enough:
# application_controller.rb def redirect_back_or_default(default) redirect_to(session.delete(:return_to) || default) end
Comments
Post a Comment