我有一个用户模型,它有一个布尔开关来指定admin t/f。我当前的应用程序控制器:
class ApplicationController < ActionController::Base
protect_from_forgery
def after_sign_in_path_for(user)
if current_user.admin?
admin_index_path
else
dashboard_index_path
end
end
end
我当前的管理员控制器:
class AdminController < ApplicationController
def index
if current_user.admin?
admin_index_path
else
home_index_path
end
end
end
当然,目标是只允许管理员用户访问管理员索引页面。当我以管理员身份登录时,重定向工作正常,但当我以非管理员用户身份导航到admin_index_path时,AdminController中出现NoMethodError#索引错误(nil:NilClass的未定义方法"admin?")。对此问题有帮助吗?我觉得可能有一个CanCan解决方案会更优雅、更安全,但我还没有找到一个很好的解释来解释如何实现这一点。想法?提前感谢!
使用before_filter
https://github.com/plataformatec/devise#controller-过滤器和辅助
class AdminController < ApplicationController
before_filter :authenticate_user!, only: [:index]
before_filter :is_admin, only: [:index]
def index
end
private
def is_admin
if user_signed_in?
if current_user.admin?
true
else
redirect_to home_index_path
end
else
redirect_to login_path
end
end
end
user_signed_in?
检查用户已登录并访问索引时current_user.admin?
检查为admin
或
def is_admin
if current_user.nil?
redirect_to login_path
else
if current_user.admin?
true
else
redirect_to home_index_path
end
end
end
使用资源而不是使用它是更通用的
def after_sign_in_path_for(资源)如果current_user.admin?admin_index_path其他的dashboard_index_path终止终止和
然后把before_filter:authenticate_user!在索引操作中。它会解决你的问题。您得到了nil类错误,因为current_user变量未设置为用户未登录。