CanCan:检查记录的权限,包括依赖性
CanCan: Check permission on record including dependency
示例模型
- 用户在 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实现吗?
刚刚找到解决方法,很简单:
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
示例模型
- 用户在 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实现吗?
刚刚找到解决方法,很简单:
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