0

我已经阅读了关于同一主题的几个问题,但没有一个能解决我的疑问或对我有用。

Pundit 无法在我的代码中找到命名空间策略,但我不明白为什么。我有一个“后端”命名空间,每当调用此“后端”中的items_controller.rb时,它都会使用app/policies/item_policy.rb,而不是app/policies/backend/item_policy.rb之一。

任何帮助将不胜感激。我在这个问题上花了很多时间。

我的app/policies/目录:

application_policy.rb
backend_policy.rb
item_policy.rb
backend/item_policy.rb

application_policy.rb

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

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

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

backend_policy.rb

class Backend::ApplicationPolicy < ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

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

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

后端/item_policy.rb

class Backend::ItemPolicy < Backend::ApplicationPolicy
  attr_reader :user, :item

  def initialize(user, item)
    @user = user
    @item = item
  end

  def index?
    raise Pundit::NotAuthorizedError, "must be logged in" unless @user.admin?
  end
end

控制器/后端/items_controller.rb

class Backend::ItemsController < Backend::ApplicationController
  before_action :set_item, only: [:show, :edit, :update, :destroy]
  after_action :verify_authorized

  # GET /backend/items
  # GET /backend/items.json
  def index
    @search = Item.search (search_params)
    @items = @search.result().page(params[:page]).per(12)
    authorize Item
  end
....
end
4

1 回答 1

2

这就是在权威代码中提取您的策略名称的方式

def find
  if object.respond_to?(:policy_class)
    object.policy_class
  elsif object.class.respond_to?(:policy_class)
    object.class.policy_class
  else
    klass = if object.respond_to?(:model_name)
      object.model_name
    elsif object.class.respond_to?(:model_name)
      object.class.model_name
    elsif object.is_a?(Class)
      object
    elsif object.is_a?(Symbol)
      object.to_s.classify
    else
      object.class
    end
    "#{klass}Policy"
  end
end

因此,要么向模型添加函数“policy_class”,要么为模型本身添加命名空间

于 2015-03-08T12:17:35.233 回答