在 Rails 6 中使用 activestorage 时,如何在重新显示表单时保留文件? [英] When using activestorage in Rails 6, how do I retain a file when redisplaying a form?

查看:32
本文介绍了在 Rails 6 中使用 activestorage 时,如何在重新显示表单时保留文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 6 中,我有一个带有文件字段的表单,我使用 activestorage 来存储文件.如果提交表单后验证失败,则会重新显示表单,显示验证错误.重新显示表单时如何保留添加到文件字段的文件,以便用户不必再次将文件添加到表单?

In Rails 6 I have a form with a file field and I am using activestorage to store the file. If validations fail after submitting the form, the form is redisplayed showing the validation errors. How can I retain the file added to the file field when redisplaying the form so that the user does not have to add the file again to the form?

rails 5 已经有一个类似的问题:Active Storage:在表单重新显示时保留/缓存上传的文件的最佳实践,但是那里的解决方案仅适用于 Rails 5.

There is already a similar question for rails 5: Active Storage: Best practice to retain/cache uploaded file when form redisplays, however the solution there only applies to Rails 5.

推荐答案

由于 Rails 6 在分配时不存储文件,我找到的解决方法是在文件字段上启用直接上传.这将在提交表单之前通过 javascript 上传文件.

Since Rails 6 does not store the file on assignment, the workaround I found was to enable direct upload on the file field. This will upload the file via javascript before the form submission.

= f.file_field :doc, direct_upload: true

为此,您还需要将 activestorage.js 添加到您的包中,如 活动存储指南.

For this to work, you also need to add activestorage.js to your bundle as described in the Active Storage guide.

更改后,您可以使用问题中描述的方法Active Storage:当表单重新显示时保留/缓存上传文件的最佳实践.这意味着将 signed_id 添加到表单的隐藏字段中,如下所示:

After that change one can use the method described in the question Active Storage: Best practice to retain/cache uploaded file when form redisplays. That means adding the signed_id to your form in a hidden field as follows:

= f.file_field :doc, direct_upload: true
= f.hidden_field :doc, value: f.object.doc.signed_id if f.object.doc.attached?

这篇关于在 Rails 6 中使用 activestorage 时,如何在重新显示表单时保留文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆