Tre*_*ott 20 authentication action ruby-on-rails devise
按照此处的指南,我使用迁移为我的数据库添加了一个布尔属性:
rails generate migration add_admin_to_user admin:boolean
Run Code Online (Sandbox Code Playgroud)
我通过Rails控制台将我的帐户配置为管理员(admin = 1).我有一个控制器,我想限制只为管理员访问某些操作(新建,编辑,创建和销毁).
我也有普通用户,我只想限制只在这个控制器中管理员访问这些操作.目前,我正在使用代码:
before_filter :authenticate_user!, :only => [:new, :edit, :create, :destroy]
Run Code Online (Sandbox Code Playgroud)
这限制了对注册用户的访问 - 如何更进一步并要求管理员?
Wil*_*Ayd 33
您可以轻松实现自己的before_filter,以便只允许使用.admin访问管理员用户?与您的用户模型关联的方法.例如:
before_filter :verify_is_admin
private
def verify_is_admin
(current_user.nil?) ? redirect_to(root_path) : (redirect_to(root_path) unless current_user.admin?)
end
Run Code Online (Sandbox Code Playgroud)
您需要在before过滤器中定义自己的方法,然后在调用之前检测用户是否是该方法中的admin:authenticate_user!
before_filter :custom_method, :only => [:new, :edit, :create, :destroy]
private
def custom_method
authenticate_user!
if current_user.admin
return
else
redirect_to root_url # or whatever
end
end
Run Code Online (Sandbox Code Playgroud)
你会想要authenticate_user!检查current_user变量之前的步骤.
伊恩.
| 归档时间: |
|
| 查看次数: |
8518 次 |
| 最近记录: |