Redirect to previous page after sign in

When using ‘Devise’ for your authentication mechanism, ¬†you may need to redirect to the previous webpage after signing in.

To do this:

class Users::SessionsController < Devise::SessionsController
  layout 'user'

  after_filter :store_location

  def store_location
    # store last url - this is needed for post-login redirect to whatever the user last visited.
    return unless request.get?
    if request.path != "/users/sign_in" &&
        request.path != "/users/sign_up" &&
        request.path != "/users/password/new" &&
        request.path != "/users/password/edit" &&
        request.path != "/users/confirmation" &&
        request.path != "/users/sign_out" &&
        !request.xhr? # don't store ajax calls
      session[:previous_url] = request.fullpath
    end
  end

  #Take me to the referring page after sign in
  def after_sign_in_path_for(resource)
    session[:previous_url] || root_path
  end

end

 

Advertisements