我的用户模型中有一个admin:boolean
字段,如果用户是管理员,他们可以检查我的控制器,然后才可以编辑任何内容。
如何修改before_action :authenticate_user!, only: [:edit]
以检查用户是否为管理员?
答案 0 :(得分:7)
您可以在authenticate_user之后添加另一个将被调用的操作!检查当前用户是否具有管理员权限。
class YourController
# first call authenticate_user! to check if user is signed in
before_action authenticate_user!, only: [:edit]
# if user is signed (current_user exist), check if he is admin
before_action authenticate_admin!, only: [:edit]
def authenticate_admin!
# check if current user is admin
unless current_user.admin
# if current_user is not admin redirect to some route
redirect_to 'some_public_route'
end
# if current_user is admin he will proceed to edit action
end
end