2010-03-02 28 views
4

非常基本的用户模型,我希望管理用户:管理所有CanCan宝石|不能:索引,用户

其他不能:索引,用户和其他选项,但是当我试图阻止非管理员用户查看用户索引,admin用户也无法访问。

这是我ability.rb

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new #guest user 

    can :manage, :all if user.role == "admin" #if user.admin? can :manage, :all 
    can :assign_role, User 

    else 
     can :read, :all 
     can :create, User 


     cannot :assign_role, User 
     cannot :index, User 

     can [:show, :edit, :update], User do |current_user| 
       user.id == current_user.id || user.role == "admin" 
      end 



    end 
end 

我能做些什么来阻止被阻止所有用户都从用户的索引?

问候

+2

不错的代码汤那里。那还有什么关系? – tadman 2010-03-02 23:09:46

回答

3

蹊跷的if-else代码。

if user.role == "admin" 
    can :manage, :all 
    can :assign_role, User 

else 
    can :read, :all 
    can :create, User 


    cannot :assign_role, User 
    cannot :index, User 
    can [:show, :edit, :update], User do |current_user| 
    user.id == current_user.id || user.role == "admin" 
    end 

end 

而且你也不必拒绝非管理员用户明确分配角色(不能:assign_role,User)。

+0

我是正确的思想,关于admin IF语句停止的第一个“能”,因为我没有和IF状态,并开始与 后可以正确的:管理:所有IF USER.ROLE ==“ADMIN” 无论如何,谢谢UZZZ,很好的帮助! – MrThomas 2010-03-03 11:26:53

+0

是的,“if”语句只适用于一行代码(如果它位于行尾) – uzzz 2010-03-03 12:23:40