【发布时间】:2016-08-14 18:13:43
【问题描述】:
我以前用过Pundit Gem,但我从来没有尝试过我现在想做的事情,出于某种原因,Pundit 不高兴。
我的目标是在我的“索引”(Foos)页面上创建一个带有“创建”(Foo)表单的模式。因此,我需要实例化一个空的 Foo 对象以使模态表单起作用。
我遇到的问题是 Pundit 在我远程提交表单时抛出错误。错误是:
Pundit::NotDefinedError - 找不到 nil 策略
我试图了解为什么会发生这种情况,但我还没有解决它。
这是我的 foos_controller.rb#index:
...
def index
@foo = Foo.new
authorize @foo, :new?
@foos = policy_scope(Foo)
end
...
然后我有以下 'before_action' 过滤器运行我的其他操作,即“创建”
...
before_action :run_authorisation_check, except: [:index]
def run_authorisation_check
authorize @foo
end
...
我在 foo_policy.rb 中使用的策略:
....
def index?
user.has_any_role? :super_admin
end
def create?
user.has_any_role? :super_admin
end
def new?
create?
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
if user.has_any_role? :super_admin
scope.all
end
end
end
....
在我提交表单之前,错误不会出现。任何熟悉 Pundit 的人都可以帮助指导我了解我做错了什么吗?
更新
完整的 foos_controller.rb
class FoosController < ApplicationController
def index
@foo = Foo.new
authorize @foo, :create?
@foos = policy_scope(Foo)
end
def new
@foo = Foo.new
end
def create
@foo = Foo.new(foo_params)
respond_to do |format|
if @foo.save
flash[:notice] = I18n.t("foo.flash.created")
format.json { render json: @foo, status: :ok }
else
format.json { render json: @foo.errors, status: :unprocessable_entity }
end
end
end
private
before_action :run_authorisation_check, except: [:index]
def foo_params
params.fetch(:foo, {}).permit(:bar)
end
def run_authorisation_check
authorize @foo
end
end
【问题讨论】:
-
看来你可能没有设置
@foo的值,在调用:run_authorisation_check方法之前,你能展示你完整的控制器吗? -
@oreoluwa 我更新了我的问题
标签: ruby-on-rails ruby-on-rails-5 pundit