gpt4 book ai didi

ruby-on-rails - cancancan authorize_resource 未按预期工作

转载 作者:行者123 更新时间:2023-12-04 05:48:24 29 4
gpt4 key购买 nike

我收到了一个简单的 cancancan 授权的意外行为。

能力.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 Controller (部分显示)
class ServiceOrdersController < ApplicationController
authorize_resource

def show
@service_order = ServiceOrder.includes(:service_order_details).find(params[:id])
end

end

这不起作用,因为它让 Controller 显示任何 service_order 记录,而不仅仅是那些由 current_user 拥有的记录。

唯一可行的方法是我手动授权 Controller 添加:
authorize! :show, @service_order

像这样:
  def show
@service_order = ServiceOrder.includes(:service_order_details).find(params[:id])
authorize! :show, @service_order
end

这毫无意义,因为 authorize_resource应该这样做。

最佳答案

正在发生的是authorize_resource发生在表演行动之前,并且因为 @service_order尚未设置,它正在检查类,并且用户确实有权显示 ServiceOrder只是在约束下。

Adding authorize_resource will install a before_action callback that calls authorize!, passing the resource instance variable if it exists. If the instance variable isn't set (such as in the index action) it will pass in the class name. For example, if we have a ProductsController it will do this before each action.

authorize!(params[:action].to_sym, @product || Product)



from Cancancan documentations

您需要做的是 load_and_authorize_resource正如widjajayd所建议的那样。或者(如果您不想使用 cancancan 默认加载操作)执行 before_filterauthorize_resource 之前使用您的自定义方法手动加载资源称呼。

关于ruby-on-rails - cancancan authorize_resource 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45038310/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com