切换“ActionController::Parameters.action_on_unpermitted_parameters = :raise"关于特定的控制器方法? [英] Toggle "ActionController::Parameters.action_on_unpermitted_parameters = :raise" on specific controller methods?
问题描述
我要使用
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_parameters = :raise"关于特定的控制器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!