Search code examples
ruby-on-railsformsrails-activestorage

Why does Rails form multiple: true change submitted param form


I'm playing with ActiveStorage and trying to upload some files locally. Everything works great with the code below, but only if I remove multiple: true from the form. When it is on the form, I get an unpermitted param "files" error in the console. The unpermitted param comes from the way the form is submitting the hash.

Without multiple: true the hash lists attachments as an array (this is the working version): "article"=>{"files"=>[#<ActionDispatch::Http::UploadedFile:0x007fb4e8e287f0

But with it turned on it it removes the array: "article"=>{"files"=>#<ActionDispatch::Http::UploadedFile:0x007fb4eb07b7d0

What is causing this form behavior and how can I fix it?

I got the code sample from Engine Yard and here is the project code:

<h3>Attach files to this post</h3>
<%= form_with model: @article, local: true do |f|  %>
    <div class="form-row">
        <%= f.label :file_upload, 'Attach a file' %>
        <%= f.file_field :files, multiple: true %>
    </div>

    <%= f.submit %>
<% end %>

<h3>Attached files</h3>
<% @article.files.each do |file| %>
    <%= link_to file.blob.filename, url_for(file) %>
<% end %>

Solution

  • When you use multiple: true you need to permit an array explicit in the article_params for :files:

    For example:

    params.require(:article).permit(:author, :text, files: [])
    

    You can read more under Action Controller

    Good luck!