Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

How To: redirect to a specific page on successful sign in

BigMcLargeHuge edited this page · 16 revisions
Clone this wiki locally

redirect back to current page after signin?

See How to: redirect to a specific page on successful sign in and sign out.

redirect back to current page after oauth signin?

This is pretty straight forward, for an oauth sign in, request.env['omniauth.origin'] is automatically set. You can also fall back to whatever you'd like:

class ApplicationController < ActionController::Base
  def after_sign_in_path_for(resource)
    request.env['omniauth.origin'] || stored_location_for(resource) || root_path
  end
end

redirect back to current page without oauth signin?

class ApplicationController < ActionController::Base
  protect_from_forgery   

  def after_sign_in_path_for(resource)
    sign_in_url = new_user_session_url
    if request.referer == sign_in_url
      super
    else
      stored_location_for(resource) || request.referer || root_path
    end
  end
end

If you don't put stored_location_for before request.referer you'll get some weird behaviour and sometimes, you won't get to the stored location.

Preventing redirect loops

Because the code for after_sign_in_path_for above only checks if request.referer == sign_in_url, these methods (which call after_sign_in_path_for) will also have to be overridden (else you will encounter redirect loops):

  • Devise::PasswordsController#after_resetting_password_path_for
  • Devise::RegistrationsController#after_sign_up_path_for
  • Devise::RegistrationsController#after_update_path_for

This can be done like so:

# routes.rb
devise_for :users, controllers: { registrations: 'users/registrations', passwords: 'users/passwords' }

# users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
  protected
    def after_sign_up_path_for(resource)
      signed_in_root_path(resource)
    end

    def after_update_path_for(resource)
      signed_in_root_path(resource)
    end
end

# users/passwords_controller.rb
class Users::PasswordsController < Devise::PasswordsController
  protected
    def after_resetting_password_path_for(resource)
      signed_in_root_path(resource)
    end
end
Something went wrong with that request. Please try again.