2
votes

I am building a custom image upload form in Rails 3 (paperclip / carrierwave is not an option for our setup) and need to do the classic "persist image on validation fail" scenario. What is the "best practice" way to do this in Rails 3?

Summary:

  1. User fills out form with image
  2. User click "send form"
  3. Form validation fails
  4. User should now see the image they uploaded in the form and not need to select it again
2
Read the Carrierwave source codeiwasrobbed
You would have to implement something like carrierwave does. Look at the carrierwave readme under "Making uploads work across form redisplays". github.com/jnicklas/carrierwave/blob/master/README.mdDevin M
Thanks for the suggestions guys - do any of you have an idea where in the source code this would be located? Im having a hard time finding it...Houen
Houen, did you ever figure this out. I'm trying to update my hack job to fix this better. Using Paperclip.bokor
Sadly, no - I actually ended up using Carrierwave after all.Houen

2 Answers

1
votes

If you are doing it from scratch, you have to put the file into the uploads directory (or create a new directory inside it to store different versions), and store the temporary file name into one not-persisted field of your model.

For example, that not-persisted field could be named photo_cache_dir:

attr_accessible :foo, :bar, :photo_cache_dir
attr_accessor :photo_cache_dir

In the template you just check for that field to be present:

@your_model.photo_cache_dir.present?

... and in that case, using your own logic, display the uploaded photo.

I don't know if this is the best practice, but it's what I'm using and it works very well.

1
votes

The file_upload_cache gem is compatible with carrierwave and works in cases that carrierwave does not work.

It also works standalone, without using carrierwave.

The documentation is here: https://github.com/kenmazaika/file_upload_cache

Disclosure: I authored this gem.