我正在构建rails应用程序,它有一些角色\功能分离。我决定使用cancancan + devise,但我不知道如何设置标准用户角色?
class User < ActiveRecord::Base
ROLES = %i[admin moderator author banned]
end发布于 2015-06-25 10:50:06
您可以对您的用户模型执行回调:
class User < ActiveRecord::Base
after_create :assign_default_role
def assign_default_role
add_role(:default_role) if self.roles.blank?
end
end如果after_create不合适,请尝试另一个回调,更多信息here
发布于 2016-01-15 22:30:46
在定义能力时,我们使用名为“user”的能力作为默认用户权限。换句话说,没有其他角色的用户将获得默认的能力集。
我们还对未登录的访问者使用一组“guest”权限。
发布于 2016-01-15 22:52:37
您可以使用以下模式来简化Ability类。注意,这里"default“角色的定义规则非常简单,因为它只是在没有角色的情况下登录的用户。
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
# this is abitilites for anonymous user
can :read, Post
return unless user.persisted?
# ok, now we know that this user is logged in and can define common abilities
can :create, Post
# and after it we can define abilities for different roles
# user.roles here should return name of roles for user,
# like [:admin, :moderator]
user.roles.each { |role| self.public_send(role, user) if respond_to?(role) }
end
def admin(user)
# abitlites for admin here
end
def moderator(user)
# abilities for moderator here
end
endhttps://stackoverflow.com/questions/31037642
复制相似问题