如何在定义CanCan能力时调用模型方法?

时间:2011-02-13 21:16:59

标签: ruby-on-rails-3

我在使用CanCan能力模型中定义的方法时遇到问题:

模型

def Car
    def can_paint?
        ..some conditions, return true or false..
    end
end

能力

can :paint, Car, :user_id => user.id, Car.can_paint?

CarsController

def paint
    @car = ..find the car..
    return redirect_to jobs_path unless can? :paint, @car
    ...
end
调用paint动作时出现

错误

/.../app/models/ability.rb:11: syntax error, unexpected '\n', expecting tASSOC 
#error points to the line in ability defined above

如果我从该异能中删除Car.can_paint?,则表示没有错误。

问题:

  1. 如何在能力中使用can_paint?

  2. 在定义能力时,是否无法访问为模型找到的实际实例,即@car 而不必使用Car以便我可以写:
    can :paint, Car, :user_id => user.id ***if @car.can_paint?***

1 个答案:

答案 0 :(得分:2)

can方法需要检查条件的哈希值。在您的示例中,当您调用它时:

can :paint, Car, :user_id => user.id, Car.can_paint?

基本上是通过了这个:

can :paint, Car, {:user_id => user.id, true}

哪个不是有效的哈希,可能是expecting tASSOC错误的来源。 (您也在类上调用实例方法 - 但这不是真正的问题)

但是,您可以将块作为条件传递,因此类似以下内容可用于检查实际对象:

can :paint, Car, :user_id => user.id do |car|
  car.can_paint?
end

这将正确检查用户是否有权绘制汽车实例。

供参考,请关注CanCan的文档,因为它们提供了一些很好的例子 - https://github.com/ryanb/cancan/wiki/Defining-Abilities