Search code examples
ruby-on-railscancan

CanCan gem | cannot :index, User


Very basic user model, I wish the admin user to :manage all

else cannot :index, User and some other options, but when I try and block non admin users from viewing the user index, the admin user also has not access.

this is my 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

What can I do to stop all users being blocked from User index?

Regards

Dan


Solution

  • Something wrong with if-else in code.

    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
    

    And also you don't have to deny non-admin user to assign role obviously (cannot :assign_role, User).