我在简单的cancancan授权中遇到了意外行为。
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the passed in user here. For example:
#
user ||= User.new # guest user (not logged in)
if user.is_admin?
can :manage, :all
elsif user.is_standard?
can :manage, ServiceOrder, {user_id: user.id}
can :manage, ServiceOrderDetail, :service_order => { :user_id => user.id }
end
service_order.rb控制器(部分显示)
class ServiceOrdersController < ApplicationController
authorize_resource
def show
@service_order = ServiceOrder.includes(:service_order_details).find(params[:id])
end
end
这种方式不可行,因为它让控制器展示任何服务订单记录,而不仅仅是当前用户拥有的订单。
唯一有效的方式是手动授权控制器,添加以下内容:
authorize! :show, @service_order
像这样:
def show
@service_order = ServiceOrder.includes(:service_order_details).find(params[:id])
authorize! :show, @service_order
end
这没有意义,因为
authorize_resource
应该做这个。
before_action :fetch_user
与authorize_resource
交换位置,以便在授权尝试之前先加载用户。 - mike927