她是我的application.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将它们重新定向回用户。
问题是:如果用户已登录但未获得授权,我该如何处理此逻辑。
答案 0 :(得分:13)
我添加了一些条件来完成这项工作。
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