default ActiveRecordAdditions#can method action to :read and use 'scoped' if 'where' is not available

This commit is contained in:
Ryan Bates
2010-04-15 23:18:49 -07:00
parent 3c68a911d0
commit 37f482e8d5
4 changed files with 53 additions and 6 deletions

View File

@@ -191,9 +191,7 @@ module CanCan
# can :read, Article, :visible => true
# conditions :read, Article # returns { :visible => true }
#
# For example, you can use this in Active Record find conditions to only fetch articles the user has permission to read.
#
# Article.where(current_ability.conditions(:read, Article))
# Normally you will not call this method directly, but instead go through ActiveRecordAdditions#can method.
#
# If the ability is not defined then false is returned so be sure to take that into consideration.
# If the ability is defined using a block then this will raise an exception since a hash of conditions cannot be

View File

@@ -2,8 +2,30 @@ module CanCan
# This module is automatically included into all Active Record.
module ActiveRecordAdditions
module ClassMethods
def can(ability, action)
where(ability.conditions(action, self) || {:id => nil})
# Returns a scope which fetches only the records that the passed ability
# can perform a given action on. The action defaults to :read. This
# is usually called from a controller and passed the +current_ability+.
#
# @articles = Article.can(current_ability)
#
# Here only the articles which the user is able to read will be returned.
# If the user does not have permission to read any articles then an empty
# result is returned. Since this is a scope it can be combined with any
# other scopes or pagination.
#
# An alternative action can optionally be passed as a second argument.
#
# @articles = Article.can(current_ability, :update)
#
# Here only the articles which the user can update are returned. This
# internally uses Ability#conditions method, see that for more information.
def can(ability, action = :read)
conditions = ability.conditions(action, self) || {:id => nil}
if respond_to? :where
where(conditions)
else
scoped(:conditions => conditions)
end
end
end