By default, Devise will redirect you to the root path after sign in. but sometimes we would like to redirect to the previous page where the anonymous user wanna access. This can be done by the following.
1. Create the app/helpers/sessions_helper.rb
module SessionsHelper def deny_access store_location redirect_to new_user_session_path end # add back anyone_signed_in? method after Oliver's comment @ 2011-03-12 def anyone_signed_in? !current_user.nil? end private def store_location session[:return_to] = request.fullpath end def clear_stored_location session[:return_to] = nil end end
2. Include the session helper and customize the Devise after_sign_in_path_for() in app/controllers/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery include SessionsHelper # Customize the Devise after_sign_in_path_for() for redirecct to previous page after login def after_sign_in_path_for(resource_or_scope) case resource_or_scope when :user, User store_location = session[:return_to] clear_stored_location (store_location.nil?) ? "/" : store_location.to_s else super end end end
3. Request user to login in your controller
... def new if !anyone_signed_in? deny_access else @service = Service.new @title = "Create New Service" end end ...
- Rails Devise only redirects to a fixed path. Need to redirect back where the user came from when authentication was triggered.
- StackOverflow – Devise override redirect after form submit
- How To: Redirect to a specific page on successful sign in
Update @ 2011-09-23: If you are using omniauth, the following piece of code may help. Thanks for Allan. =D
def after_sign_in_path_for(resource_or_scope) if request.env['omniauth.origin'] request.env['omniauth.origin'] end end