DEV Community

Wedson Lima
Wedson Lima

Posted on

Active Storage: Retaining and removing uploaded files on form submission

Working with active storage, you may encounter a common problem when submitting the form; Rails will replace or remove all previously uploaded files.

Here, I show a simple approach to:

  • not replace or delete the previously uploaded files on form submission;
  • remove a specific file while editing a form;

We will use the signed_id from active record.

# your model
has_many_attached :files
Enter fullscreen mode Exit fullscreen mode
// _form.html
= f.input :files, input_html: { class: 'form-control', multiple: true }

- if f.object.files.attached?
  - f.object.files.each do |file|
    = f.input :files, input_html: { value: file.signed_id, multiple: true }, as: :hidden

    li
      = link_to file.filename, rails_blob_path(file, disposition: 'attachment')
      '
      button.btn.btn-danger.remove-uploaded-file[data-uploaded-file-signed-id=file.signed_id] X
Enter fullscreen mode Exit fullscreen mode
jQuery(function ($) {
  $('.remove-uploaded-file').on('click', function (e) {
    e.preventDefault();

    const $parent = $(this).parent();
    $parent.remove();

    const signedId = $(this).data('uploaded-file-signed-id');
    const $fileInput = $('input[value="' + signedId + '"]');

    $fileInput.remove();
  });
});
Enter fullscreen mode Exit fullscreen mode

This will give you something like this

Image description

Top comments (0)