验证失败时如何保留文件字段值 [英] How to keep file field value when validation failed

查看:49
本文介绍了验证失败时如何保留文件字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有文件字段的经典Rails 3表单,一切正常,上传作品并将数据保存到数据库.

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

当验证失败(例如,标题丢失)时,用户将被带回render :action => new的表单.普通的.但是这里的问题是,用户不得不再次选择文件.

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?

推荐答案

通常,您不希望在运行验证后才处理文件,或者要重复存储可能没有相关记录的文件.像回形针和attachment_fu这样的宝石就可以做到这一点.

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 %>

有道理吗?

这篇关于验证失败时如何保留文件字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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