[英]Devise/cancan redirect admin issue
我有一个带有布尔开关的用户模型来指定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身份登录时,重定向工作正常,但是当我以非管理员用户身份导航到admin_index_path时(在nil:NilClass上未定义的方法“ admin?”),我在AdminController#index错误中遇到NoMethodError。 对这个问题有帮助吗? 我觉得可能有一个CanCan解决方案会更优雅,更安全,但是我还没有找到如何实现此目标的很好的解释。 有什么想法吗? 提前致谢!
使用before_filter
https://github.com/plataformatec/devise#controller-filters-and-helpers
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?
访问索引时检查是否为管理员
要么
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变量设置为未登录的用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.