Restricting an administrator from destroying their own account with cancan

Here is a snippet of my code from my feature class

if user.admin?
      can :manage, :all
      can :destroy, :all if != current_user

I am sure you can understand what I am trying to do here. I understand that destruction is included in management, and I repeat myself there. Any suggestions?

EDIT Yjerem's answer was correct, and I just modified it to fit my code. Here is how it looks.

 if user.admin?
      can :manage, :all
      cannot :destroy, User, :id => user.id

As Yerem said, in cancan, the priority of abilities indicates that the ability determines the lower trump card above them, so the administrator can control everything except what is defined under it using the code above.

+3
source share
2 answers

, !

, cannot:

if user.admin?
      can :manage, :all
      cannot :destroy, User, :id => current_user.id

cannot , .

+5

- ( , Account/User):

def initialize(user)
  ...

  if user.admin?
    can :manage, :all
    can :destroy, Account do |account|
      account.user != user # admin can destroy all Accounts/Users except his own
    end
  end

  ...
end
+1

All Articles