Skip to content

How To: Redirect back to current page after sign in, sign out, sign up, update

Tony Han edited this page Jul 27, 2013 · 9 revisions

Code

In ApplicationController write following:

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.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

Note that if you happen to have before_filter :authenticate_user! in your ApplicationController you will need to use before_filter :store_location rather than after_filter :store_location and make sure to place it ahead of before_filter :authenticate_user!. This is due to the likelihood that if a user fails to be authenticated they will by default be redirected to /users/sign_in and thus not appropriately set the session[:previous_url] value.

Alternatively, you can simply modify the regular expression comparison (/\/users/ in the above example) to only match the specific urls that you wish to skip, such as /\/users\/sign_in/.

You may also want to add

def after_update_path_for(resource)
  session[:previous_url] || root_path
end

or

def after_sign_out_path_for(resource)
  session[:previous_url] || root_path
end

Be aware, however, that there may be resources available to a signed-in user that would not be available to the anonymous user, so use the after_sign_out_path_for with caution.

Explanation

We only want to keep track of a previous url if it is not a /users url. This way, it will redirect to the last url that is not involved in the user sign in, sign up, or update process.

Clone this wiki locally