我正在使用Rails 4,devise,角色模型和CanCanCan。
是否有可能在ability.rb中定义一些角色所共有的能力?
例如,每个登录的用户都可以浏览他们自己的配置文件页面吗?那么角色除了这些共同的能力之外,还有特定的能力?
这是如何工作的呢?我是否需要在角色模型中为共同能力创建一个角色,然后允许每个用户拥有多个角色,从而使他们获得共同的能力以及特定于角色的能力?
例如,在我的ability.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)所以,我希望学生们能够读到客人能读到的同样的东西。是否有一种方法可以说,学生可以做的一切,新的用户和用户注册的能力(以及学生的具体能力)?
发布于 2015-09-03 09:29:44
您可以通过这样的函数调用在角色中进行某种组合。
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
endauthenticated函数将包含任何角色的通用能力,以及它只需要调用的每个角色(这是一种继承,任何学生都可以做通过身份验证的用户可以做的事情,再加上他的能力)
发布于 2015-09-03 08:24:12
我在这里为你的理解增加了一个能力类的例子。您可以轻松地理解代码和阅读注释。您的代码似乎不太好,我可以指出一件事,您不应该通过profile来管理角色,您应该使用user来分配或管理roles。
如果您想给一组用户同样的能力,那么您可以使用这种类型的||条件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希望这能帮助你完成你的任务。
发布于 2015-09-03 07:50:59
https://stackoverflow.com/questions/32305405
复制相似问题