问题描述
Paperclip 具有验证器方法,用于验证文件的存在、大小和内容类型.但是有没有办法在保存记录之前验证文件的内容?
Paperclip has validator methods for validating the presence, size, and content-type of files. But is there a way to validate the contents of the file before the record is saved?
我尝试执行 validate :my_method
并从 [attachment].path
在 my_method
中打开文件,但当然失败了,因为在保存记录之前,附件尚未移动到文件系统中的最终放置位置.
I tried doing validate :my_method
and opening the file from [attachment].path
in my_method
, but of course that fails because the attachment hasn't been moved to its final resting place in the file system before the record is saved.
编写自定义 Paperclip 后处理器似乎是一种选择,因为它可以在保存记录之前访问属于附件的 File 对象,但是出现故障的处理器不会在保存记录之前使记录无效.
Writing a custom Paperclip post-processor seemed like an option because it has access to the File object belonging to the attachment before the record is saved, but a failing processor won't invalidate the record before it's saved.
有什么好办法吗?我还能如何确保我的应用程序中只有符合要求的文件?(如果文件无效,我是否可以使用其他回调来优雅地删除整个记录?)
Is there a good way to do this? How else can I make sure that I only have conforming files living in my app? (Are there other callbacks I can use that will gracefully delete the entire record if the file isn't valid?)
哦.特别是,从 after_save 回调中引发 ActiveRecord::Rollback 会做一些理智的事情吗?
edit: Ooh. In particular, will raising ActiveRecord::Rollback from an after_save callback do something sane?
推荐答案
啊,但是您可以在保存记录之前从验证器访问 File 对象,方法是调用 [attachment].to_file
.在 my_method
中针对 [attachment].to_file.path
(而不是 attachment.path
)运行我的解析器似乎工作得很好.
Ah, but you can access the File object from a validator before the record is saved, by calling [attachment].to_file
. Running my parser against [attachment].to_file.path
(instead of attachment.path
) in my_method
seems to work just fine.
每个 https://stackoverflow.com/questions/7047183/how-to-set-an-attribute-for-a-model-instance-in-a-paperclip-post-process-callback, [attachment].queued_for_write[:original].path
也可能是一个选项.
Per https://stackoverflow.com/questions/7047183/how-to-set-an-attribute-for-a-model-instance-in-a-paperclip-post-process-callback, [attachment].queued_for_write[:original].path
might also be an option.
这篇关于使用 Paperclip gem 验证上传时的附件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!