Vasseurth
Vasseurth

Reputation: 6486

How do you give a user permission with CanCan

I'm using CanCan for user permission. I set it up well and have:

def initialize(user)
# Define abilities for the passed in user here. For example:
user ||= User.new # guest user (not logged in)

    if user.role? :admin
        can :manage, :all

    else        
        can :create, Post           
        can :read, Post
    end

    def role?(role)
        return !!self.roles.find_by_name(role.to_s.camelize)
    end

My question is how do I actually give a user a role, meaning right now all the users fall into the else category... how do i make a user associate with :admin?

Upvotes: 0

Views: 458

Answers (1)

David Sulc
David Sulc

Reputation: 25994

The easy way to do this is to add a string role attribute to your user.

Then, in your user model:

def role?(arg)
  self.role.to_sym == arg.to_sym
end

And delete the role? method in the Ability model, you don't need it for your example.

Upvotes: 2

Related Questions