How to check abilities in CanCan

Can? method

After you define the Abilities, you can use the can? method to check a user’s permissions for a given action and object in the controller or view.

The can? method takes in two parameters:

can? action, object

where:

  • action includes all the actions set in the Abilities class including user-defined actions.
  • object is the class the object permissions need to be checked on.
can? :create, @project

Cannot? method

The cannot? method performs the opposite check of the can? method.

can? :destroy, @project

Checking class

To check permissions for a class, use:

<% if can? :create, Project %>
  <%= link_to "New Project", new_project_path %>
<% end %>

Note: If a hash of conditions exist for that condition, the check will return true. e.g., If the permissions were set for Project

can :read, Project, :user_id => user.id

The check method will return true.

can? :read, Project

It is not possible to check the can method completely as not enough detail is present. Therefore, it checks if any user can read a project and, therefore, returns true.

It is important to do another check for the hash conditions once an instance becomes available.

This is credited to the controller index action. Since the authorize_resource before the filter has no instance to check on, it uses the project class. If authorization fails at the time, it is impossible to filter the results during fetching. Therefore, passing a class to can? will always return true.

Copyright ©2024 Educative, Inc. All rights reserved