ruby-on-railsstrong-parameters

Rails strong params, how to allow empty params?


I have set these strong params:

def my_model_params
  params.require(:my_model).permit(:field)
end

But sometimes the form is sent empty and I get this error:

param is missing or the value is empty: my_model

How can I allow the form to be empty when still using strong params?


Solution

  • Use fetch.

    Returns a parameter for the given key. If the key can’t be found, there are several options: With no other arguments, it will raise an ActionController::ParameterMissing error; if a second argument is given, then that is returned (converted to an instance of ActionController::Parameters if possible); if a block is given, then that will be run and its result returned.

    def my_model_params
      params.fetch(:my_model, {})
            .permit(:field)
    end
    

    The reason you want to use this over params.permit(my_model: [ :field ]) is that it will always return an ActionController::Parameters instance instead of nil.