在登录或注册后设计重定向回原始位置? [英] Devise redirect back to the original location after sign in or sign up?

查看:18
本文介绍了在登录或注册后设计重定向回原始位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我使用 Devise Gem 进行身份验证.如果有人想在没有登录的情况下打开页面,那么它会重定向到 sign_in 页面,然后在登录后返回到用户尝试打开的页面.我使用 Redirect loop with Devise after_sign_in_path_for 链接为我的问题,但它对我不起作用.

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

它不会将我重定向回我想要打开的页面.例如:如果我想打开127.0.0.1:3000/post/2/edit",登录后不返回此页面.

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.

推荐答案

要寻求的最佳资源是官方 repo/wiki/issues,然后是 SO.您找到的答案已过时.

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

答案如下:https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-注册,更新

只需在ApplicationController 对于版本devise > 3.2.1 添加以下内容:

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

这篇关于在登录或注册后设计重定向回原始位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆