CanCan:检查记录的权限,包括依赖性

CanCan: Check permission on record including dependency

示例模型

权限设置

can :read, Car, :car_pool => { :users => { :id => user.id } }
can :create, CarPickup

用例

目标是让用户为他的一辆车创建一个新的 CarPickup。该视图可能类似于:

= form_for @car_pickup do
  = f.association :car, :collection => Car.accessible_by(current_ability)

问题

保存用户时,应验证当前用户是否可以访问通过上述表格传递的汽车。有没有一种优雅的方式来做一些事情:

def create
  @car_pickup = CarPickup.new(params[:car_pickup])

  authorize :create, @car_pickup

  if @car_pickup.car
    Car.accessible_by(current_ability).include?(@car_pickup.car)
  end

  if @car_pickup.save
  # ...
end

解决方案尝试/更多问题

刚刚找到解决方法,很简单:

can :read, Car, :car_pool => { :users => { :id => user.id } }
can :create, CarPickup, :car => { :car_pool => { :users => { :id => user.id } }

# Add this line in order for it to work when trying to save a
# `CarPickup` without any `Car`.
can :create, CarPickup, :car => nil