Rails + Devise:如何覆盖before_filter“authenticate_user!”的重定向

时间:2013-05-23 14:30:59

标签: ruby-on-rails devise

我在Rails 3和Devise的最新版本上,我在AdminControllerauthenticate_user!之前有一个过滤器我需要在request.referrer之前存储一个会话变量重定向,以便我可以在尝试继续时将其发送回/ admin页面。我会在哪里覆盖authenticate_user!

我想做的是这个,但我不知道在哪里定义它:

def authenticate_user!
  session[:return_to] = request.request_uri
  super
end

2 个答案:

答案 0 :(得分:3)

您实际上并不需要这样做,设计会为了这个目的而尊重after_sign_in_path

在您的应用程序控制器中:

before_filter :set_return_path 

def after_sign_in_path_for(resource) 
  session["user_return_to"] || root_url 
end

def set_return_path
  unless devise_controller? || request.xhr? || !request.get?
    session["user_return_to"] = request.url
  end
end

来自设计助手:

# The default url to be used after signing in. This is used by all Devise
# controllers and you can overwrite it in your ApplicationController to
# provide a custom hook for a custom resource.
# def after_sign_in_path_for(resource_or_scope)

答案 1 :(得分:0)

Matt答案的替代方案,不需要在每个页面视图上记录返回页面:

在application_controller.rb中:

# Only remembers the page immediately before we 
# redirect them for auth, instead of every page view

def authenticate_user!
  session["user_return_to"] = request.fullpath
  super
end

# Deletes the return path as soon as it's used, so 
# they aren't accidentally redirected back again
# next time they login

def after_sign_in_path_for(resource)
  session.delete("user_return_to") || root_path
end