【问题标题】:Pundit::NotAuthorizedError / Problem with pundit authorizePundit::NotAuthorizedError / 权威授权问题
【发布时间】:2020-08-05 08:04:40
【问题描述】:

我正在尝试在表单中更新用户的地址,但我不明白为什么我无权执行,这是我的代码:

class AddressesController < ApplicationController
  def update
    @address = current_user.addresses.last
    authorize @address
    @address.update!(address_params)
  end

  private

  def address_params
    params.require(:address).permit(:first_name, :last_name, :city, :country, :postcode, :phone_number, :street_address, :optional_address, :user_id)
  end
end


class AddressPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.all
    end

    def update?
      true
    end
  end
end

这是错误:

Pundit::NotAuthorizedError in AddressesController#update 不允许更新?这个地址

【问题讨论】:

    标签: ruby-on-rails ruby pundit


    【解决方案1】:

    您已经在嵌套的 Scope 类中定义了 update? 方法,但它应该直接在策略类中定义。

    而不是这个:

    class AddressPolicy < ApplicationPolicy
      class Scope < Scope
        def resolve
          scope.all
        end
    
        def update?
          true
        end
      end
    end
    

    你需要这样做:

    class AddressPolicy < ApplicationPolicy
      class Scope < Scope
        def resolve
          scope.all
        end
      end
    
      def update?
        true
      end
    end
    

    【讨论】:

    • 您当前的代码只能调用ApplicationPolicy#update?,它必须返回false
    • 看看the Pundit README,你会看到resolve方法应该在里面,但是这些谓词方法不是。
    • 哦,Tom Lord,谢谢你,我不知道我怎么会错过那个错误啊哈:)
    • 我们都去过那里:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多