0

I have something that looks like this in my ability class

def initialize(staff)
   staff ||= Staff.new
   can :manage, Store do |store|
      store.staff_privileges.select(&:owner?).map(&:staff_id).include? staff.id
   end
end

I am not sure why staff.can? :manage would return true here because I thought the above block should only get executed on the instance of store and not on the class itself

staff = Staff.first
staff.can? :manage, Store #true
staff.can? :manage, Store.first #false, because there is no staff_privileges associated to this store
denniss
  • 17,229
  • 26
  • 92
  • 141

1 Answers1

0

From https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks

The block is only evaluated when an actual instance object is present. It is not evaluated when checking permissions on the class (such as in the index action). This means any conditions which are not dependent on the object attributes should be moved outside of the block.

Why would this be? I don't know, but I think the answer is in the "such as in the index action" bit in there? Without that behavior, the load_and_authorize_resource method cancan provides would not work for the index action.

SporkInventor
  • 3,120
  • 2
  • 16
  • 11