Hartator
Hartator

Reputation: 5145

How to keep file field value when validation failed

I have a classic rails 3 form with a file field, everything works fine, upload works and data is saved to database.

When a validation failed, for example, title is missing, then the user is sent back to the form with a render :action => new. Normal. But the problem here, is that the user have to select another time its file.

Any way to avoid that?

Upvotes: 3

Views: 3160

Answers (3)

rubyprince
rubyprince

Reputation: 17793

I know the question is old, but now the carrierwave gem has something to retain the file field when the validation fails.

https://github.com/carrierwaveuploader/carrierwave#making-uploads-work-across-form-redisplays

Basically, you will have to add a hidden_field avatar_cache if your model has an uploader mounted on avatar file. You will have to add it to the permit list in the controller (so that Rails wont restrict the field from being submitted to the server)

Upvotes: 1

coreyward
coreyward

Reputation: 80041

Typically you don't want to process files until after validations have run or you're going to repeatedly store files that possibly don't have the associated records. Gems like Paperclip and attachment_fu do this.

If you would rather store the file the first time it's submitted and is valid you can store the file and then do a quick check in your view to see if it's already set for the object you're building a form for, e.g:

<% unless foo.attachment? %>
  # file field
<% end %>

Make sense?

Upvotes: 3

fl00r
fl00r

Reputation: 83680

You can't. It is security issue.

You can hack it in some browsers, but generally you can't do it

Upvotes: 2

Related Questions