我比较新的rails(3),并且正在建立一个应用程序,使用CanCan,那里有3层的用户.
>访客 – 未注册的访问者用户
>注册并登录访客
>管理员 – 已注册并登录
访客与管理员标志
我的能力是现在的沼泽,从cancan文档复制,基本上定义了客户角色和管理角色
class Ability include CanCan::Ability def initialize(user) user ||= User.new # Guest user if user.is_admin? can :manage,:all else can :read,[Asana,Image,User,Video,Sequence] end end end
我正在寻找添加用户角色.由于我正在创建一次性的用户模型,我以为使用new_record?以确定用户是否登录.就像是:
class Ability include CanCan::Ability def initialize(user) user ||= User.new # Guest user if !user.new_record? and user.is_admin? can :manage,:all elsif !user.new_record? and !user.is_admin? can {registered user-y permissions} else can :read,Sequence] end end end
但是,它感觉不对.似乎与实际的登录编辑一样脱离了关系,并且担心它是否真的安全.
寻求建议,以更优雅的方式来做到这一点.
谢谢!
解决方法
好的问题,我用较低到更高的权限方法:
class Ability include CanCan::Ability def initialize(user) # Guest User unless user can :read,Sequence] else # All registered users can {registered user-y permissions} # Admins if user.is_admin? can :manage,:all end end end end
这样,如果明天你有其他角色要整合,你可以添加一个case语句,如下所示:
class Ability include CanCan::Ability def initialize(user) # Guest User unless user can :read,Sequence] else # All registered users can {registered user-y permissions} # Different roles case user.role when 'admin' can :manage,:all when 'manager' can :manage,[Video,Sequence] end end end end