I am using the paperclip gem to attach files to models. When you upload a file using Paperclip, the file is saved ONLY when the model is saved. Thus, if the model is invalid, the uploaded file is not saved. Is there a way to temporarily save the uploaded file, so that the user doesn't have to upload the same file if the model is invalid?
Define a before_save
method that checks if the object is valid,
if not save the file to disk, give it a unique name (create some hash)
Put that in the form you send back in a hidden field
Delete the Upload field in the form
Now in the else branch of the before_save
method check if there was a hidden_field
previous_upload or however you name it
If there is load the picture and assign it to the paperclip attribute, it can figure out the rest
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With