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
// _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
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();
});
});
This will give you something like this
Top comments (0)