她是我的应用程序.rb
class ApplicationController < ActionController::Base protect_from_forgery rescue_from CanCan::AccessDenied do |exception| flash[:error] = "You must first login to view this page" session[:user_return_to] = request.url redirect_to "/users/sign_in" end end
如果AccessDenied是throw并且用户没有登录(“工作得很好”),这会将使用重定向到登录页面,但是一旦登录就会导致重定向循环,如果登录但未经cancan授权,因为登录页面只会通过会话[:user_return_to] = request.url将它们重新定向回用户.
解决方法
我添加了一些条件来完成这项工作.
class ApplicationController < ActionController::Base protect_from_forgery #Redirects to login for secure resources rescue_from CanCan::AccessDenied do |exception| if user_signed_in? flash[:error] = "Not authorized to view this page" session[:user_return_to] = nil redirect_to root_url else flash[:error] = "You must first login to view this page" session[:user_return_to] = request.url redirect_to "/users/sign_in" end end end