Search code examples
ruby-on-railsrails-activestorage

Error attaching file with ActiveStorage "Could not find or build blob: expected attachable" got ActionDispatch::Http::UploadedFile


I'm trying to save an image from an editor plugin. params are:

<ActionController::Parameters {"file"=>[#<ActionDispatch::Http::UploadedFile:0x00007fa78416dfe0 @tempfile=#<Tempfile:/var/folders/gt/k_vyp2g13zl7l89pzl9y44vc0000gp/T/RackMultipart20200918-91605-ob1sq1.jpg>, @original_filename="folk.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file[]\"; filename=\"folk.jpg\"\r\nContent-Type: image/jpeg\r\n">], "controller"=>"admin/medias", "action"=>"create"} permitted: false>

So in my action I build my record with the attachment

@media = Media.new
@media.file = params[:file]
# @media.file.attach params[:file]  # same error
@media.save!

I get the error:

ArgumentError Exception: Could not find or build blob: expected attachable, got [#<ActionDispatch::Http::UploadedFile ..

How can I attach the submited file to the @media record?


Solution

  • The submitted params[:file] is an array of files.

    If the editor can indeed upload multiple images, make sure your Media class is configured to use has_many_attached rather than has_one_attached.

    If it should only upload one image, either change the editor or use the first item in the array.