Using the Rails Paperclip gem, how to temporarily save a downloaded file if the model is invalid

I use paperclip pearls to attach files to models. When you download a file using Paperclip, the file is saved ONLY when you save the model. Thus, if the model is invalid, the downloaded file is not saved. Is there a way to temporarily save the downloaded file so that the user does not download the same file if the model is invalid?

+5
source share
1 answer

Define a method before_savethat checks if an object is valid, if you do not save the file to disk, give it a unique name (create a hash)

Put this in the form you submit back in the hidden field

""

else before_save , hidden_field previous_upload , , ,

attr_accessor :previous_upload

def before_save
  if valid?
    if previous_upload
      paperclip_file = #Load paperclip_file from /tmp
    else
      previous_upload = nil
    end
  else
    previous_upload = "Some unique key for each upload like ip and time or such"
    # Save paperclip_file with name previous_upload to /tmp
  end
end 
+2

All Articles