Pundit::NotAuthorizedError / 专家授权问题

Pundit::NotAuthorizedError / Problem with pundit authorize

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

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 不允许更新?这个地址

您已经在嵌套的 Scope class 中定义了 update? 方法,但它应该直接在策略 class.[=14= 中定义]

而不是这个:

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