0

我的能力课上有这样的东西

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

我不确定为什么staff.can? :manage会在这里返回 true,因为我认为上面的块应该只在 store 的实例上执行,而不是在类本身上执行

staff = Staff.first
staff.can? :manage, Store #true
staff.can? :manage, Store.first #false, because there is no staff_privileges associated to this store
4

1 回答 1

0

来自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.

为什么会这样?我不知道,但我认为答案在“例如在索引操作中”位中?如果没有这种行为,cancan 提供的 load_and_authorize_resource 方法将无法用于索引操作。

于 2012-11-13T02:12:26.277 回答