Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Ability Precedence

joshuapinter edited this page Feb 9, 2012 · 7 revisions

The ability rules further down in a file will override a previous one. For example, let's say we want the user to be able to do everything to projects except destroy them. This is the correct way.

can :manage, Project
cannot :destroy, Project

It is important that the cannot :destroy line comes after the can :manage line. If they were reversed, cannot :destroy would be overridden by can :manage. Therefore, it is best to place the more generic rules near the top.

Adding can rules do not override prior rules, but instead are logically or'ed.

can :manage, Project, :user_id => user.id
can :update, Project do |project|
  !project.locked?
end

For the above, can? :update will always return true if the user_id equals user.id, even if the project is locked.

This is also important when dealing with roles which have inherited behavior. For example, let's say we have two roles, moderator and admin. We want the admin to inherit the moderator's behavior.

if user.role? :moderator
  can :manage, Project
  cannot :destroy, Project
  can :manage, Comment
end
if user.role? :admin
  can :destroy, Project
end

Here it is important the admin role be after the moderator so it can override the cannot behavior to give the admin more permissions. See Role Based Authorization.

If you are not getting the behavior you expect, please post an issue.

Additional Docs