在Rails 6中,我有一个带有文件字段的表单,并且正在使用activestorage来存储文件。如果提交表单后验证失败,则会重新显示该表单,并显示验证错误。重新显示表单时如何保留添加到文件字段中的文件,以使用户不必再次将文件添加到表单中?
对于Rails 5已经存在类似的问题:Active Storage: Best practice to retain/cache uploaded file when form redisplays,但是那里的解决方案仅适用于Rails 5。
答案 0 :(得分:0)
由于Rails 6并未在分配时存储文件,所以我发现的解决方法是在文件字段上启用直接上载。这将在提交表单之前通过javascript上传文件。
= f.file_field :doc, direct_upload: true
要执行此操作,还需要按照Active Storage guide中所述,将activestorage.js添加到您的软件包中。
更改之后,可以使用问题Active Storage: Best practice to retain/cache uploaded file when form redisplays中描述的方法。这意味着在隐藏字段中将signd_id添加到表单中,如下所示:
= f.file_field :doc, direct_upload: true
= f.hidden_field :doc, value: f.object.doc.signed_id if f.object.doc.attached?
答案 1 :(得分:0)
除了Robban答案之外,还可以用于多个附件并进行一些预览
= f.file_field :attachments, multiple: true, direct_upload: true
- f.object.attachments.each do |attach|
= f.hidden_field :attachments, value: attach.signed_id, multiple: true
= image_tag attach.preview(resize_to_limit: [100, 100]) if attach.previewable?
= image_tag attach.variant(resize_to_limit: [100, 100]) if attach.variable?