How to keep file field value when validation failed

醉酒当歌 提交于 2019-12-24 04:49:26

问题


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?


回答1:


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?




回答2:


You can't. It is security issue.

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




回答3:


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)



来源:https://stackoverflow.com/questions/5981119/how-to-keep-file-field-value-when-validation-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!