2012-07-25 49 views
1

我正在使用rails應用程序,它需要兩種不同類型的角色。一個是員工,另一個是管理員。爲用戶設置角色,使用cancan的rails

康康文檔說,它假定應用程序中有一個用戶或current_user方法。

那麼,如何使用cancan在我的應用程序中爲員工和經理設置角色?

回答

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 

而且abily這個樣子

 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 

它肯定工程...

+0

我沒有用戶類。我有Employee類,從那裏我想設置角色。 – 2012-07-25 07:31:15

+0

你有沒有安裝設計? – Kashiftufail 2012-07-25 07:37:56

+0

是的,我已經安裝設計,並將其設置到僱員模型 – 2012-07-25 07:42:28

相關問題