gpt4 book ai didi

ruby-on-rails-4 - Pundit 无法找到命名空间策略

转载 作者:行者123 更新时间:2023-12-04 17:00:14 24 4
gpt4 key购买 nike

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

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

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

我的 应用程序/政策/目录:

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

Controller /后端/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

最佳答案

这是在 pundit code 中提取您的策略名称的方式

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”添加到您的模型中,要么为模型本身命名空间

关于ruby-on-rails-4 - Pundit 无法找到命名空间策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27711583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com