如何在验证失败时保持文件字段值?

时间:2021-11-05 08:16:05

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

我有一个经典的rails 3表单和一个文件字段,一切都很好,上传工作和数据保存到数据库。

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.

例如,当验证失败时,缺少title,然后将用户发送回呈现:action => new的表单。正常的。但是这里的问题是,用户必须选择另一个时间文件。

Any way to avoid that?

有没有办法避免呢?

2 个解决方案

#1


3  

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.

通常,在验证运行之后,您不希望处理文件,或者您将重复地存储可能没有关联记录的文件。像Paperclip和attachment_fu这样的宝石可以做到这一点。

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


3  

You can't. It is security issue.

你不能。这是安全问题。

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

你可以在一些浏览器中破解它,但通常你做不到。

#1


3  

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.

通常,在验证运行之后,您不希望处理文件,或者您将重复地存储可能没有关联记录的文件。像Paperclip和attachment_fu这样的宝石可以做到这一点。

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


3  

You can't. It is security issue.

你不能。这是安全问题。

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

你可以在一些浏览器中破解它,但通常你做不到。