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
Some of the other solutions here may not work if your login form has its own page, as opposed to, e.g., a login form in the header of every page. After logging in, the user needs to go back two pages, not just one.
Devise has a nice How To on Redirecting back to the current page after sign in, sign out, update, from which the code below comes.
Storing the original URL in the session is the best option. In addition to solving the above problem of going back two pages, "Many browsers do not send [the request.referer
] header. Therefore the only robust cross-browser way to implement this functionality is by using the session."
When storing URLs in the session, it's important not to store the URL for any POST, PUT, or DELETE request, nor any XHR request, i.e. nothing to which the user can't actually be redirected.
Note that after signing out, the user's session is destroyed, so the stored URL is gone. In this case, the user can be sent back to request.referer
. This seems acceptable since most websites have a sign out link on every page, so returning to the referrer will actually work.
class ApplicationController < ActionController::Base
before_action :store_user_location!, if: :storable_location?
before_action :authenticate_user!
private
def storable_location?
request.get? && is_navigational_format? && !devise_controller? && !request.xhr?
end
def store_user_location!
store_location_for(:user, request.fullpath)
end
def after_sign_in_path_for(resource_or_scope)
stored_location_for(resource_or_scope) || super
end
def after_sign_out_path_for(resource_or_scope)
request.referrer || super
end
end