validates_attachment为可选字段 [英] validates_attachment for optional field

查看:81
本文介绍了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?

您可能遇到的问题是可以使用Procinstance 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对象是否存在,向验证提供truefalse

This basically determines if the attachment object is present, providing either true or false to the validation

这篇关于validates_attachment为可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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