Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle missing required params with StrongParameters?

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?

like image 362
Matt Huggins Avatar asked Jun 21 '14 01:06

Matt Huggins


1 Answers

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)
like image 125
Matt Huggins Avatar answered Oct 13 '22 22:10

Matt Huggins