0

The policy_scope works perfectly finding the correct policy named Admin::RemittancePolicy but authorize method not.

module Admin
  class RemittancesController < AdminController # :nodoc:
    ...

    def index
      @remittances = policy_scope(Remittance).all

      render json: @remittances
    end

    def show
      authorize @remittance

      render json: @remittance
    end

    ...
  end
end

Take a look at output error:

"#<Pundit::NotDefinedError: unable to find scope `RemittancePolicy::Scope` for `Remittance(...)`>"

Perhaps a error with pundit, I really not know how fix it. Thanks.


More information below:

# policies/admin/admin_policy.rb
module Admin
  class AdminPolicy < ApplicationPolicy # :nodoc:
    def initialize(user, record)
      @user = user
      @record = record.is_a?(Array) ? record.last : record
    end

    def scope
      Pundit.policy_scope! user, record.class
    end

    class Scope # :nodoc:
      attr_reader :user, :scope

      def initialize(user, scope)
        @user = user
        @scope = scope.is_a?(Array) ? scope.last : scope
      end

      def resolve
        scope
      end
    end
  end
end

# controllers/admin/admin_controller.rb
module Admin
  class AdminController < ActionController::API # :nodoc:
    include Knock::Authenticable
    include Pundit

    before_action :authenticate_user

    after_action :verify_authorized, except: :index
    after_action :verify_policy_scoped, only: :index

    # def policy_scope!(user, scope)
    #   model = scope.is_a?(Array) ? scope.last : scope
    #   PolicyFinder.new(scope).scope!.new(user, model).resolve
    # end

    def policy_scope(scope)
      super [:admin, scope]
    end

    def authorize(record, query = nil)
      super [:admin, record], query
    end
  end
end
Bruno Wego
  • 2,099
  • 3
  • 21
  • 38
  • 1
    What does the `show?` method look like for your `Admin::RemittancePolicy` ? You say `policy_scope` works perfectly and `authorize` works fine, but I have a feeling the error you pasted is not directly from any of the code you've provided. How about showing the full error too? – deefour Apr 30 '17 at 15:33
  • `show` does nothing now. Thanks to try help me. The complete stack here https://gist.github.com/brunowego/c9ce9a709fcec94e0d313f32dbc645ae – Bruno Wego Apr 30 '17 at 15:38
  • Only `policy_scope` are going correctly to `Admin::RemittancePolicy`. The `authorize` are going to `RemittancePolicy`. – Bruno Wego Apr 30 '17 at 15:55

1 Answers1

2

Your stacktrace says the error comes from

app/policies/admin/admin_policy.rb:9:in 'scope'

That's this:

def scope
  Pundit.policy_scope! user, record.class
end

record.class evaluates to Remittance, so if I understand what you're trying to do, you need to change scope to

def scope
  Pundit.policy_scope! user, [:admin, record.class]
end
deefour
  • 34,974
  • 7
  • 97
  • 90