[英]Rails - CanCanCan - common abilities
我正在使用Rails 4,devise,Role Model和CanCanCan。
是否可以在能力.rb中定義許多角色共有的能力?
例如,每個登錄用戶都可以CRUD自己的個人資料頁面嗎? 然后,角色在該共同能力之上還具有特定能力?
這是如何運作的? 我是否需要在角色模型中為通用功能創建一個角色,然后允許每個用戶擁有多個角色,以便他們獲得通用功能以及特定於角色的功能?
例如,在我的Capacity.rb中,我有:
class Ability
include CanCan::Ability
def initialize(user)
alias_action :create, :read, :update, :destroy, :to => :crud
# Define abilities for the passed in user here. For example:
#
user ||= User.new # guest user (not logged in)
#users who are not signed in can create registration or login
# can read publicly available projects, programs and proposals
can :read, Project, {:active => true, :closed => false, :sweep => { :disclosure => { :allusers => true } } }
# {:active => true, :closed => false && :Project.sweep.disclosure.allusers => true}
# if user role is student
if user_signed_in?
can :crud, Profile, :user_id => user.id #[for themselves]
elsif user.try(:profile).present? && user.profile.has_role?(:student)
因此,我希望學生能夠閱讀客人可以閱讀的相同內容。 有沒有辦法說學生可以做新用戶和已登錄用戶可以做的所有事情(以及學生的特定能力)?
您可以通過這樣的函數調用在角色中進行某種組合
class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
#
user ||= User.new # guest user (not logged in)
#users who are not signed in can create registration or login
# can read publicly available projects, programs and proposals
# {:active => true, :closed => false && :Project.sweep.disclosure.allusers => true}
# if user role is student
if user_signed_in?
if user.try(:profile).present? && user.profile.has_role?(:student)
student
else
authenticated
end
else
anonymous
end
end
def anonymous
can :read, Project, {:active => true, :closed => false, :sweep => { :disclosure => { :allusers => true } } }
end
def authenticated
anonymous
can :crud, Profile, :user_id => user.id #[for themselves]
end
def student
authenticated
#other student abilities
end
#other roles follow the same principal
def teacher
authenticated
end
end
經過authenticated
功能將包含任何角色的通用能力,並且需要該角色的每個角色都將調用(這是一種繼承,任何學生都可以執行經身份驗證的用戶可以添加的能力)
我在這里添加一個示例能力課程,以供您理解。 您可以輕松理解代碼並閱讀注釋。 您的代碼似乎不好,我只能指出一件事,您不應該通過profile
管理角色,而應該使用user
來分配或管理roles
。
如果要為一組用戶提供相同的功能,則可以使用這種類型的||
條件user.has_role?(:role_one) || user.has_role?(:role_two)
user.has_role?(:role_one) || user.has_role?(:role_two)
並像can :manage, [SomeClassName, SomeClassName]
那樣傳遞能力塊。
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
#Only same user can mange his Profile
can :manage, [Profile], :user_id => user.id
#Give rule wise permission
if user.admin?
can :manage, :all
elsif user.has_role?(:some_role_name)
can :manage, [SomeClassName]
elsif user.has_role?(:role_one) || user.has_role?(:role_two)
can :manage, [SomeClassName, SomeClassName]
else
can :read, :all
end
end
end
希望這可以幫助您完成任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.