ruby-on-railsruby-on-rails-5strong-parameters

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?


Solution

  • 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.