-1
class Ability
  include CanCan::Ability
  def initialize(user)
    @user = user || User.new

    can :manage, :all
    can :custom_action, User, role: 'admin'
  end
end

and in view

if can? :custom_action, @user
  SHOW SOMETHING

this if always show "SHOW SOMETHING", don't understood why it's happend.

Alex808
  • 106
  • 1
  • 10

2 Answers2

1

Well, that's because in your ability class, you give every user all rights.

You are probably looking for something like this:

def initialize(user)
  @user = user || User.new

  can :manage, :all

  # When user is an admin, grant her extra privileges
  if @user.is_admin?
    can :custom_action
  end
end

This way, you define the abilities (by using can) conditionally

Stobbej
  • 1,080
  • 9
  • 17
  • I this case (if can? :custom_action, @user(No admin)) must return false, but it return true. Or I some thig don't understood? – Alex808 Jan 25 '13 at 14:27
  • This CanCan ability config generate some thing like this. IF (any action on any object granted) || (some condition on :custom_action). So it's always True return. – Alex808 Jan 26 '13 at 18:52
0

Solution is:

class Ability include CanCan::Ability def initialize(user) @user = user || User.new

can :manage, :all
cannot :custom_action, User, role: 'admin'

end end

In view:

if can? :custom_action, @user

return 
  user = true
  admin = false

This is not perfect solution but it's works

Alex808
  • 106
  • 1
  • 10