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

前端 未结 8 2262
野趣味
野趣味 2020-12-14 07:42

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

8条回答
  •  隐瞒了意图╮
    2020-12-14 08:37

    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 your ApplicationController in app/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
    

提交回复
热议问题