切换“ActionController::Parameters.action_on_unpermitted_pa​​rameters = :raise"关于特定的控制器方法? [英] Toggle "ActionController::Parameters.action_on_unpermitted_parameters = :raise" on specific controller methods?

查看:29
本文介绍了切换“ActionController::Parameters.action_on_unpermitted_pa​​rameters = :raise"关于特定的控制器方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用

ActionController::Parameters.action_on_unpermitted_parameters = :raise

为了引发异常,传入了不允许的参数,但我只想在特定的控制器方法上执行此操作,而不是在/config/中设置它并将其应用于整个环境.有什么办法吗?

To raise an exception unpermitted parameters are passed in, but I only want to do this on specific controller methods, instead of setting it in /config/ and having it apply to the whole environment. Is there any way to do so?

推荐答案

更新:(从 Mike 的回答中获取灵感)

Update: (taking inspiration from Mike's answer)

要限制仅对一组控制器动作进行更改并将其恢复为调用动作之前类属性所持有的原始值,我们可以使用 around_action

To restrict the change only for a set of controller actions and to revert it back to the original value that the class attribute was holding before the action being invoked, we can use around_action

class SomeController < ApplicationController
  around_action :raise_action_on_unpermitted_parameters, only: %i[create update]

  def index
    # ...
  end

  def create
    # ...
  end

  def update
    # ...
  end

  private

  def raise_action_on_unpermitted_parameters
    original = ActionController::Parameters.action_on_unpermitted_parameters
    ActionController::Parameters.action_on_unpermitted_parameters = :raise
    yield
  ensure
    ActionController::Parameters.action_on_unpermitted_parameters = original
  end
end

这篇关于切换“ActionController::Parameters.action_on_unpermitted_pa​​rameters = :raise"关于特定的控制器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆