Here I\'m using Devise Gem for authentication. If someone want to open page without login then it redirect to sign_in page and after signed in it back to the page which user
As of Devise 4, it worked seamlessly for me:
Devise automatically redirects on sign in and sign up as long as you store the location of the current page using devise's
store_location_for(resource)
. To do this, edit yourApplicationController
inapp/controllers/application_controller.rb
. Add:# saves the location before loading each page so we can return to the # right page. If we're on a devise page, we don't want to store that as the # place to return to (for example, we don't want to return to the sign in page # after signing in), which is what the :unless prevents before_filter :store_current_location, :unless => :devise_controller? private # override the devise helper to store the current location so we can # redirect to it after loggin in or out. This override makes signing in # and signing up work automatically. def store_current_location store_location_for(:user, request.url) end
Add the following to the
ApplicationController
to make sign out redirect:private # override the devise method for where to go after signing out because theirs # always goes to the root path. Because devise uses a session variable and # the session is destroyed on log out, we need to use request.referrer # root_path is there as a backup def after_sign_out_path_for(resource) request.referrer || root_path end
gem 'devise', '~> 4.4.0'
Create sessions_controller.rb: class SessionsController < Devise::SessionsController
Add the following (modifying the regex if your login url isn't /users)
def before_login
session[:previous_url] = request.fullpath unless request.fullpath =~ /\/users/
end
def after_login
session[:previous_url] || root_path
end
Notice that this does not work if you've got /users/dashboard or other locations under /users. Might want to get more specific with the regex.