Devise redirect back to the original location after sign in or sign up?

devise, ruby-on-rails

Solution

The best resource to seek is the official repo/wiki/issues, and then SO. The answer you found is out of date.

Here is the answer: https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update

Just add the following in ApplicationController for versions devise > 3.2.1:

    # This example assumes that you have setup devise to authenticate a class named User.
class ApplicationController < ActionController::Base
  before_action :store_user_location!, if: :storable_location?
  # The callback which stores the current location must be added before you authenticate the user 
  # as `authenticate_user!` (or whatever your resource is) will halt the filter chain and redirect 
  # before the location can be stored.
  before_action :authenticate_user!

  private
    # Its important that the location is NOT stored if:
    # - The request method is not GET (non idempotent)
    # - The request is handled by a Devise controller such as Devise::SessionsController as that could cause an 
    #    infinite redirect loop.
    # - The request is an Ajax request as this can lead to very unexpected behaviour.
    def storable_location?
      request.get? && is_navigational_format? && !devise_controller? && !request.xhr? 
    end

    def store_user_location!
      # :user is the scope we are authenticating
      store_location_for(:user, request.fullpath)
    end
end

And then to redirect after signing in, you have to override this method:

def after_sign_in_path_for(resource_or_scope)
  stored_location_for(resource_or_scope) || super
end

Problem

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 try to open. I use Redirect loop with Devise after_sign_in_path_for link for my problem but it does not work for me. ``` def after_sign_in_path_for(resource) params[:next] || super end ``` It doesn't redirect back me to the page which I want to open. for example: If I want to open "127.0.0.1:3000/post/2/edit", it doest not back to this page after signed in.

Original source