Skip to content

How To: Redirect to a specific page on successful sign in out

Jhonny Toledo edited this page May 26, 2022 · 17 revisions

Imagine we have the following devise user User.

Setting up the controller for sign in

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  after_filter :store_action
  
  def store_action
    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
      store_location_for(:user, request.fullpath)
    end
  end
end

The stored location is used by the after_sign_in_path_for helper. By setting it the helper will use it.

In this case the user will be redirected to the last viewed page before he is authenticated. You can replace request.fullpath by anything you want.

Setting up the controller for sign out

# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  def after_sign_out_path_for(resource_or_scope)
    whatever_path
  end
end

For logout it doesn't work the same way as login. So replace whatever_path by any path you want to redirect the user after logout.

Clone this wiki locally