问题
I want to use
ActionController::Parameters.action_on_unpermitted_parameters = :raise
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?
回答1:
Update: (taking inspiration from Mike's answer)
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
回答2:
I'm not sure Wasif's answer will work properly because it never sets it back. At a minimum I think you want this:
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
begin
ActionController::Parameters.action_on_unpermitted_parameters = :raise
yield
ensure
ActionController::Parameters.action_on_unpermitted_parameters = :log
end
end
end
And even then I'm not sure you won't encounter a race condition where it's set to raise on different controller actions accidentally if you're using a multithreaded server like Puma.
来源:https://stackoverflow.com/questions/47693233/toggle-actioncontrollerparameters-action-on-unpermitted-parameters-raise