Best way to handle missing parameters with StrongParameters?

I have a Upload ActiveModel class that has one attribute: filename . Since only one attribute, leaving the field blank in the form, causes an increase in error when using the following code in my controller:

 class UploadsController < ApplicationController def create @upload = Upload.new(upload_params) # ... end private def upload_params params.require(:upload).permit(:filename) end end 

The best workaround I came up with is rescue in the upload_params method, for example:

 def upload_params params.require(:upload).permit(:filename) rescue ActionController::Parameters.new end 

Alternatively, I suppose, I could add a hidden field to ensure that the filename field is always set to something regardless, for example:

 = simple_form_for upload do |f| = f.input :filename, as: :hidden, input_html: { value: '' } = f.input :filename, as: :file = f.submit 'Upload' 

Is there a better way to handle a user not filling out any form attributes?

+6
source share
1 answer

The numbers that I find the answer immediately after posting my question. :)

It seems that the ActionController::StrongParameters#fetch method does what is needed, for example:

 params.fetch(:upload, {}).permit(:filename) 
+7
source

Source: https://habr.com/ru/post/971124/


All Articles