[英]Cancancan default role
我正在構建具有某些角色\\功能分離的Rails應用程序。 我決定使用cancancan + devise,但我不知道如何設置標准用戶角色?
class User < ActiveRecord::Base
ROLES = %i[admin moderator author banned]
end
您可以在User模型上進行回調:
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不適合,請嘗試另一個回調,更多信息在這里
在定義能力時,我們使用稱為“用戶”的能力作為默認用戶權限。 換句話說,沒有其他角色的用戶將獲得默認功能集。
我們還對未登錄的訪問者使用一組“來賓”權限。
您可以使用以下模式簡化Ability
類。 注意,在這里為“默認”角色定義規則非常簡單,因為它只是在沒有角色的情況下登錄用戶的。
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
end
代替回調,我將在字段或枚舉中設置默認值。
class User
include Mongoid::Document
...
field :roles, type: Array # , default: [:am]
extend Enumerize
enumerize :roles, in: [:superadmin, :am, :salesrep], multiple: true #, default: :am
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.