0

I'm uploading an Image to my Image model using formtastic Gem.

User model has many images

I've created my form using formtastic gem:

= semantic_form_for @user, :remote => true, :html => { :class => 'formtastic' } do |f|
  = f.semantic_fields_for :images, @image do |image|
    = image.input :file
             :label => false,
             :as => :file

It is required to upload an image. The form has two more fields Name and description! After choosing a file to upload it shows the chosen file name.

If I fill out all the required fields and hit submit it works perfectly fine but If I hit submit before filling out all required field then form will ask me to fill out required fields and also asks me choose the file again.

Expected behavior is that form should only ask me to fill out missing required field and it should remember previously chosen file. Does anyone know why it's doing this?

Any help will be greatly appreciated

1 Answers1

0

When the form is submitted, the file is attached to the request. When the error page returns, the values of the form fields are supplied by the server from the submitted info to rewrite the page. However, the server does not know anything about where the file came from on your system, so cannot re-fetch the file from your system to pre-populate the form. Anything that would pre-populate the file field would have to have the ability to go into the filesystem on your computer. This is only allowed if you browse to the file yourself. A couple of solutions are proposed here:

How to persist file upload fields after a rails validation error.

The first couple answers recommend using an attachment-management gem like Paperclip; if you want to avoid using another gem I like the third, which recommends client-side validation of the data through javascript - basically prevent the user from submitting the form to the server with bad info in the first place. Of course you still want to validate on the server side.

Community
  • 1
  • 1
Fred Willmore
  • 4,386
  • 1
  • 27
  • 36