我想阻止未登录的用户使用 CanCanCan 访问 URL
我的能力模型是
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.admin?
can :manage, :all
elsif user.roles.size > 0
can :manage, User, :id => user.id
else
can :read, :all
cannot :read, :User
end
end
end
我的用户控制器是
class UsersController < ApplicationController
load_and_authorize_resource
def index
@users = User.paginate(page: params[:page],:per_page => 5)
end
def new
# @user = User.new
end
...
end
当我以访客用户身份访问该页面时。我在我的应用程序控制器中看到了用户索引页面,而不是被此代码重定向到登录
rescue_from CanCan::AccessDenied do |exception|
if user_signed_in?
flash[:error] = "Access denied!"
redirect_to root_url
else
flash[:error] = "Please Sign in"
redirect_to new_user_session_path
end
end
CanCanCan 工作并停止对控制器中其他操作的访问,而不是用于索引。