3

Here is a snippet of my code from my ability class

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

I am sure that you can figure out what I am trying to do here. I realize that destroy is included in manage and I am repeating myself there. Any suggestions?

EDIT Yjerem's answer was the correct one and I just changed it to fit my code. This is what it looks like.

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

As Yjerem also said, in cancan, ability precedence states that the ability defined lower down trump the ones over them so an admin can manage all except what is defined under it using the code above.

Sako Kassabian
  • 145
  • 1
  • 7

2 Answers2

5

Read Ability Precedence, there's an example there just for you!

Basically what you want is the cannot method:

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

Because the cannot rule is below the more general one, it overrides it.

Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
1

I would try something like this (assuming you have an Account/User model):

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
mbreining
  • 7,739
  • 2
  • 33
  • 35
  • While I got no errors in my text editor for this. if user.admin? can :manage, :all can :destroy, User do |u| u.id != user.id end It still was giving me errors. I am going to take a look at the precedence documentation real quick. – Sako Kassabian May 10 '11 at 21:22