module CanCan::ControllerAdditions
This module is automatically included into all controllers. It also makes the “can?” and “cannot?” methods available to all views.
Public Class Methods
Source
# File lib/cancan/controller_additions.rb, line 295 def self.included(base) base.extend ClassMethods base.helper_method :can?, :cannot?, :current_ability end
Public Instance Methods
Source
# File lib/cancan/controller_additions.rb, line 379 def can?(*args) current_ability.can?(*args) end
Use in the controller or view to check the user’s permission for a given action and object.
can? :destroy, @project
You can also pass the class instead of an instance (if you don’t have one handy).
<% if can? :create, Project %> <%= link_to "New Project", new_project_path %> <% end %>
If it’s a nested resource, you can pass the parent instance in a hash. This way it will check conditions which reach through that association.
<% if can? :create, @category => Project %> <%= link_to "New Project", new_project_path %> <% end %>
This simply calls “can?” on the current_ability. See Ability#can?
.
Source
# File lib/cancan/controller_additions.rb, line 387 def cannot?(*args) current_ability.cannot?(*args) end
Convenience method which works the same as “can?” but returns the opposite value.
cannot? :destroy, @project
Source
# File lib/cancan/controller_additions.rb, line 356 def current_ability @current_ability ||= ::Ability.new(current_user) end
Creates and returns the current user’s ability and caches it. If you want to override how the Ability
is defined then this is the place. Just define the method in the controller to change behavior.
def current_ability # instead of Ability.new(current_user) @current_ability ||= UserAbility.new(current_account) end
Notice it is important to cache the ability object so it is not recreated every time.