【发布时间】:2012-07-25 16:00:32
【问题描述】:
我正在开发一个 Rails 应用程序,它需要两种不同类型的角色。一个是员工,另一个是管理员。
Cancan 文档说它假定应用程序中有一个 user 或 current_user 方法。
那么如何使用 cancan 在我的应用中为员工和经理设置角色?
【问题讨论】:
标签: ruby-on-rails cancan
我正在开发一个 Rails 应用程序,它需要两种不同类型的角色。一个是员工,另一个是管理员。
Cancan 文档说它假定应用程序中有一个 user 或 current_user 方法。
那么如何使用 cancan 在我的应用中为员工和经理设置角色?
【问题讨论】:
标签: ruby-on-rails cancan
这样做
在应用程序助手中写这个
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
确实有效...
【讨论】: