8

I have an Upload ActiveModel class that has one attribute: filename. Since there's only one attribute, leaving the field blank on the form ends up raising an 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've come up with is to rescue in the upload_params method, e.g.:

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 no matter what, e.g.:

= 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 of handling the user not filling out any of the form attributes?

Matt Huggins
  • 81,398
  • 36
  • 149
  • 218

1 Answers1

9

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

It looks like the ActionController::StrongParameters#fetch method does what's needed, e.g.:

params.fetch(:upload, {}).permit(:filename)
Community
  • 1
  • 1
Matt Huggins
  • 81,398
  • 36
  • 149
  • 218