我正在开发一个rails应用程序,它需要两种不同类型的角色。一个是员工,另一个是管理员。
Cancan文档说它假设应用程序中有user或current_user方法。
那么如何在我的应用程序中使用cancan为员工和经理设置角色?
答案 0 :(得分:2)
这样做
在应用程序帮助程序中写这个
def is_employee?(user)
emp_role = Role.find(:first, :conditions => ["name = ?", "Employee"])
return user.roles.include?(emp_role)
end
def is_admin?(user)
admin_role = Role.find(:first, :conditions => ["name = ?", "Admin"])
return user.roles.include?(admin_role)
end
看起来像这样
class Ability
include CanCan::Ability
include ApplicationHelper
def initialize(user)
# Define abilities for the passed in user here. For example:
#
user ||= Employee.new # guest user (not logged in)
if is_admin?(user)
can :manage, :all
# cannot :manage, IpAddress
elsif is_employee?(user)
#your code
end
对于定义角色,请参阅
http://stackoverflow.com/questions/10222400/rails-adding-an-admin-role-using-devise-who-can-see-all-the-users/10222813#10222813
一定有用......