Toggle “ActionController::Parameters.action_on_unpermitted_parameters = :raise” on specific controller methods?

陌路散爱 提交于 2021-01-28 04:31:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!