2

示例模型

  • 用户在 0..* 个拼车中
  • 每辆车在 1 个拼车中
  • 每辆皮卡有1辆车

权限设置

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 } } }
    

    如果在未选择产品的情况下保存表单,则会中断。对于这个解决方案,需要有一种方法来指定if not nil

  • 第二次授权调用:

    authorize! :read, @car_pickup.car if @car_pickup.car
    
  • 可以can?(:read, @car_pickup)理解为accessible_by对单条记录吗?

  • 这可能使用 load_resource 来实现吗?

4

1 回答 1

0

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

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
于 2015-03-03T10:40:55.323 回答