validates_attachment为可选字段
我有一个可选的uload字段,可以将其保留为空.但是,当使用它时,我想验证附件的大小和内容.因此,我在模型中使用了此验证:
I have an uload field which is optional, it can be left empty. But when it is is used, I want to validate the size and content of the attachment. So I use this validation in the model:
validates_attachment :attachment, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }, size: { in: 0..500.kilobytes }
这在有附件的情况下有效,但在保留为空的情况下将失败.如何确保仅在有附件的情况下验证?
This works when there is an attachment, but fails when it is left empty. How can I make sure it only validates when there is an attached file?
此处提到的解决方案不幸地无法正常工作.
The solutions mentioned here are not working unfortunately.
您提供的链接可以为您提供我的建议-使用if:
参数
The link you provided is giving you what I would suggest - using the if:
argument
-
if:
if:
在验证中使用if:
基本上可以让您确定验证器将触发的条件.我从链接中看到,伙计们正在使用if: :avatar_changed?
您可能遇到的问题是可以使用Proc
或instance method
确定条件;而且这些人正在avatar
上使用一种方法(尽管是内置方法),所以不太可能产生想要的结果.
The problem you've likely encountered is you can either use a Proc
or instance method
to determine the condition; and as these guys are using a method on avatar
(albeit an inbuilt one), it's not likely going to yield the result you want.
我会这样做:
validates_attachment :attachment, content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }, size: { in: 0..500.kilobytes }, if: Proc.new {|a| a.attachment.present? }
这基本上确定了attachment
对象是否存在,向验证提供true
或false
This basically determines if the attachment
object is present, providing either true
or false
to the validation