Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Rails Paperclip gem, how to temporarily save the uploaded file if the model is invalid

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?

like image 577
gsmendoza Avatar asked Nov 05 '22 20:11

gsmendoza


1 Answers

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 
like image 157
nasmorn Avatar answered Nov 15 '22 06:11

nasmorn