更智能的回形针验证 [英] Smarter paperclip validations

查看:63
本文介绍了更智能的回形针验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails应用程序中使用回形针,并在模型中进行了以下三个验证

I'm using paperclip in a rails app and have the following three validations in my model

validates_attachment_presence :photo                    
validates_attachment_size :photo, :less_than=>1.megabyte
validates_attachment_content_type :photo, :content_type=>['image/jpeg', 'image/png', 'image/gif'] 

如果用户忘记添加附件,则所有三个验证都将失败,因此,将向用户显示以下三个错误:

If the user forgets to add an attachment, all three validations fail and thus, the user is presented with the following three errors:

# Photo file name must be set.
# Photo file size file size must be between 0 and 1048576 bytes.
# Photo content type is not included in the list

我认为最好在这种情况下仅显示第一个错误,因为其他两个错误纯粹是后果性的...我希望用户仅在添加了附件但没有看到第二个错误的情况下才这样做不符合验证条件.

I think it would be best to just show the first error in this instance since the other two errors are purely consequential... I would prefer the user to only ever see the second two errors if an attachment has been added but doesn't meet the validation criteria.

我确定没有做这种事情的预烘焙验​​证,并且通过阅读vendor/plugins/paperclip/lib/paperclip.rb中的代码,我看到validates_attachment_size方法支持:unless参数,如图所示:

I'm certain there is no pre-baked validation that does this sort of thing and from reading the code in vendor/plugins/paperclip/lib/paperclip.rb I see that the validates_attachment_size method supports the :unless parameter as shown:

def validates_attachment_presence name, options = {}
  message = options[:message] || "must be set."
  validates_presence_of :"#{name}_file_name", 
                        :message => message,
                        :if      => options[:if],
                        :unless  => options[:unless]
end

所以,我在想可以做以下事情:

So, I was thinking that I could do something like the following:

validates_attachment_size :photo, :less_than=>1.megabyte, :unless=> :photo.blank

但这破坏了应用程序.任何人都有做这种事情的经验吗?将对回形针源代码做出很好的贡献.

But that breaks the app. Anyone have any experience of doing this sort of thing? Would be a nice contribution to the paperclip source code.

我尝试使用此:

validates_attachment_size :photo, :less_than=>1.megabyte, 
     :unless=> Proc.new { |image| image[:photo].nil? }

尽管效果不佳,但我已经成功上传了5 mb mp3的音频,并已通过验证.但这很有希望,因为当用户未附加照片时错误消息不会出现.

It doesn't quite work though as I've just managed to upload a 5mb mp3 with this validation in place. But it's promising as the error message doesn't appear when the user has not attached a photo.

推荐答案

validates_attachment_size :photo, :less_than => 1.megabyte, 
  :unless => Proc.new { |imports| imports.photo_file_name.blank? }

这篇关于更智能的回形针验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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