CanCan with block将授予Class?

时间:2012-11-13 00:03:05

标签: ruby-on-rails cancan

我的能力课中有一些看起来像这样的东西

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

1 个答案:

答案 0 :(得分: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.

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