开发者

How to call model method when defining CanCan abilitry?

I have a problem using a method defined on a model in CanCan abilities:

model

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

ability

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

error occurs when the paint action is called

/.../app/models/ability.rb:11:开发者_运维技巧 syntax error, unexpected '\n', expecting tASSOC 
#error points to the line in ability defined above

If I remove Car.can_paint? from the ability, then there is no error.

Questions:

  1. How to use the can_paint? in the abilities?

  2. When defining abilities, is there no way to access the actual instance found for the model, i.e. @car instead of having to use Car so that I could write:

    can :paint, Car, :user_id => user.id ***if @car.can_paint?***


The can method takes a hash of conditions to check on. In your example, when you call this:

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

It is essentially passing this:

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

Which is not a valid hash, and likely the source of the expecting tASSOC error. (You are also calling an instance method on a class - but that's not the real issue here)

However, you can pass a block as a condition, so something like the following would work to check the actual object:

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

This will correctly check if a user has permission to paint an instance of a car.

For reference, keep an eye on CanCan's docs, as they provide some pretty good examples - https://github.com/ryanb/cancan/wiki/Defining-Abilities

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜