我已经阅读了关于同一主题的几个问题,但没有一个能解决我的疑问或对我有用。
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