Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 216
nao Avatar asked Jun 28 '26 01:06

nao


1 Answers

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.

like image 121
Mike Desjardins Avatar answered Jun 30 '26 16:06

Mike Desjardins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!