16

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.

cseelus
  • 1,447
  • 1
  • 20
  • 31
  • Did you manage to do something about this? – Marek Lipka Jun 27 '18 at 05:34
  • Unfortunately not. Still sticking with Shrine, which works great and has some other great features Active Storage is still missing, like uploading files as data URIs. – cseelus Jun 27 '18 at 18:01
  • @cseelus what's wrong with the solution dmitry posted below? I know it will stop working in Rails 6, but it works. And it can easily be removed when 6.0 drops next year. – stephenmurdoch Oct 09 '18 at 22:25

2 Answers2

17

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

Dmitry Semenyuk
  • 3,459
  • 1
  • 17
  • 12
  • 2
    Dmitry I want to buy you many beers right now, you saved my sanity! Thanks! – michalvalasek Jul 19 '18 at 08:58
  • 2
    For anyone who wants to use this, be aware that this is unfortunately not compatible with new changes in Rails master, that store newly-uploaded files on save rather than assignment https://github.com/rails/rails/pull/33303 – cseelus Jul 19 '18 at 22:30
  • Fortunately, that breaking change will be part of Rails 6, which is only a distant future. – Dmitry Semenyuk Aug 13 '18 at 15:16
  • Rails 5.2.1 now has the signed_id value : ) – Dominic Aug 13 '18 at 18:53
  • 1
    If anyone has a solution for this issue in Rails 6, please answer this question: https://stackoverflow.com/questions/56649565/when-using-activestorage-in-rails-6-how-do-i-retain-a-file-when-redisplaying-a – Robban Jun 18 '19 at 12:52
  • When I tried this, I receive a `ActiveSupport::MessageVerifier::InvalidSignature` exception (Rails 6.1.3.1) – jpheos Apr 16 '21 at 07:35
2

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 %>
equivalent8
  • 13,754
  • 8
  • 81
  • 109
  • where in the Rails API docs are you seeing that the hidden_field helper accepts a "multiple: true" option? Also I'm unaware of the HTML spec allowing such an attribute on inputs – SupaIrish Jan 14 '21 at 05:01
  • 1
    sorry this is probably a typo (you are right multiple is not an option + multiple is not needed as I'm looping through the photos with #each) let mi fixit. ( `multilple: true` removed) – equivalent8 Jan 14 '21 at 08:49
  • With Rails 7.0.4, **it didn't work without** `multiple: true`. Thanks. – user2553863 Nov 06 '22 at 20:17