在 Rails 6 中使用 activestorage 时,如何在重新显示表单而不上传时保留文件?

发布于 2025-01-16 14:31:33 字数 1547 浏览 0 评论 0原文

我想知道的很简单:
如何使用 ActiveStorage 在 Rails6 中重新提交表单时保留上传的文件?

我已经检查了下面的类似问题。
使用时Rails 6中的activestorage,如何在重新显示表单时保留文件?

其中建议的解决方案摘要如下:

Active Storage 在保存记录后存储附件,而不是 立即地。因此,如果您想在验证后保留分配的文件 错误,您必须上传并保存文件。

例如,

def update
  ...
  # `obj` is your model that using `has_one_attached`.
  if(obj.update)
    redirect_to ...
  else
    obj.attachment_changes.each do |_, change|
      if change.is_a?(ActiveStorage::Attached::Changes::CreateOne)
        change.upload
        change.blob.save
      end
    end
    ...
  end
end

https://medium.com/@TETRA2000/active-storage-how-to-retain-uploaded-files-on-form-resubmission-91b57be78d53

或者,使用 direct_upload:

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

通过使用这些解决方案,是的,我在重新显示表单时设法保留了一个文件。 然而,这些都违背了此公关意图。公关说

识别无效文件已经没有什么用处了 运至仓库:

您可以使用大小验证来限制单个文件的成本 可以添加到您的 AWS 账单中,但如果该文件之前存储过 验证运行后,无论如何您都会承担其成本。

因此,我不想上传文件以在验证后保留它。
如何在不上传文件和保存 blob 的情况下保留文件? 我无法使用 CarrierWave。

What I'd like to know is very simple:
How to retain uploaded files on form resubmission in Rails6 with ActiveStorage?

I have checked the below as a similar question.
When using activestorage in Rails 6, how do I retain a file when redisplaying a form?

The summary of suggested solution in it is like this:

Active Storage store attachments after the record is saved rather than
immediately. So, if you want to persist assigned file after validation
error, you must upload and save the file.

For example,

def update
  ...
  # `obj` is your model that using `has_one_attached`.
  if(obj.update)
    redirect_to ...
  else
    obj.attachment_changes.each do |_, change|
      if change.is_a?(ActiveStorage::Attached::Changes::CreateOne)
        change.upload
        change.blob.save
      end
    end
    ...
  end
end

https://medium.com/@TETRA2000/active-storage-how-to-retain-uploaded-files-on-form-resubmission-91b57be78d53

or, use direct_upload:

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

By using these solutions, yeah, I managed to retain a file when redisplaying a form.
However, these are against this pr intention. pr says

It’s of little use to identify an invalid file after it’s already been
shipped off to storage:

you might use a size validation to limit the cost that a single file
can add to your AWS bill, but if the file is stored before
validations run, you incur its cost regardless.

So, I don't want to upload file to persist it after validation.
How can I retain the file without uploading file and saving blob?
I cannot use CarrierWave.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文