Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active Storage: Best practice to retain/cache uploaded file when form redisplays

When uploading files with Active Storage, when a file is finished uploading and the form gets redisplayed, for example when the validation for that form fails for some reason, the file is gone.

Is there a way to cache or retain it between form redisplays? Shrine has a nice Plugin for that purpose, I'm looking for something similar for Active Storage.

like image 702
cseelus Avatar asked May 15 '18 23:05

cseelus


People also ask

How does active storage work in Rails?

Active Storage uses two tables in your application's database named active_storage_blobs and active_storage_attachments . After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables.

How does active storage work?

Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.


2 Answers

for those looking for has_many_attached solution

https://github.com/rails/rails/issues/35817#issuecomment-484158884

<% if @product.photos.attached? %>
  <% @product.photos.each do |ph| %>
    <%= f.hidden_field :photos, value: ph.signed_id %>
  <% end %>
<% end %>
like image 89
equivalent8 Avatar answered Sep 18 '22 08:09

equivalent8


Here's a solution to make ActiveStorage files persist on form redisplay: f.hidden_field :image, value: f.object.image.signed_id if f.object.image.attached? f.file_field :image

like image 45
Dmitry Semenyuk Avatar answered Sep 21 '22 08:09

Dmitry Semenyuk