Method: CanCan::Ability#can

Defined in:
lib/cancan/ability.rb

#can(action = nil, subject = nil, *attributes_and_conditions, &block) ⇒ Object

Defines which abilities are allowed using two arguments. The first one is the action you’re setting the permission for, the second one is the class of object you’re setting it on.

can :update, Article

You can pass an array for either of these parameters to match any one. Here the user has the ability to update or destroy both articles and comments.

can [:update, :destroy], [Article, Comment]

You can pass :all to match any object and :manage to match any action. Here are some examples.

can :manage, :all
can :update, :all
can :manage, Project

You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.

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

See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions are also used for initial attributes when building a record in ControllerAdditions#load_resource.

If the conditions hash does not give you enough control over defining abilities, you can use a block along with any Ruby code you want.

can :update, Project do |project|
  project.groups.include?(user.group)
end

If the block returns true then the user has that :update ability for that project, otherwise he will be denied access. The downside to using a block is that it cannot be used to generate conditions for database queries.

You can pass custom objects into this “can” method, this is usually done with a symbol and is useful if a class isn’t available to define permissions on.

can :read, :stats
can? :read, :stats # => true

IMPORTANT: Neither a hash of conditions nor a block will be used when checking permission on a class.

can :update, Project, :priority => 3
can? :update, Project # => true

If you pass no arguments to can, the action, class, and object will be passed to the block and the block will always be executed. This allows you to override the full behavior if the permissions are defined in an external source such as the database.

can do |action, object_class, object|
  # check the database and return true/false
end


144
145
146
# File 'lib/cancan/ability.rb', line 144

def can(action = nil, subject = nil, *attributes_and_conditions, &block)
  add_rule(Rule.new(true, action, subject, *attributes_and_conditions, &block))
end