在对某些参数添加限制后,Rails Pundit仅在创建操作时无法找到nil策略

时间:2018-07-21 15:58:57

标签: ruby-on-rails permissions pundit

我修改了我的Goal.rb模型之一,以仅允许管理员编辑一个字段。在此更新之前,此模型及其中的所有操作均在起作用。此更新也适用于编辑操作,但在创建操作返回时

Pundit::NotDefinedError in GoalsController#create unable to find policy of nil 我希望这只是语法错误,我不明白为什么它不起作用,因为没有更改模型/策略文件名,只有参数和策略设置(对编辑操作有效)

我以为可能是因为我在创建@goal时在@goal上调用了该策略,但是如果不是这样,我还要如何检查那里的权限?

goals_controller.rb:

def create
    @goal = Goal.new(permitted_attributes(@goal))
#stuff
    authorize @goal

    respond_to do |format|
      if @goal.save
#            format.json { render :show, status: :created, location: @goal }
      else
#            format.json { render json: @goal.errors, status: :unprocessable_entity }
      end
    end
  end

def update
    authorize @goal
    update_params = permitted_attributes(@goal)
  #
    end
    respond_to do |format|
      if @goal.update(update_params)
#            format.json { render :show, status: :ok, location: @goal }
      else
#            format.json { render json: @goal.errors, status: :unprocessable_entity }
      end
    end
  end

1 个答案:

答案 0 :(得分:0)

我刚刚意识到,您可以调用新课程的权限。我已经读过三遍,但只有在发布问题后,它才会单击。

我试图检查@goal的允许参数,该参数尚不存在并且显示nil策略,但是在这种情况下,使用Pundit可以对Class的允许参数进行检查:

@goal = Goal.new(permitted_attributes(目标))