validates_attachment for optional field

早过忘川 提交于 2019-12-08 07:50:43

问题


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.


回答1:


The link you provided is giving you what I would suggest - using the if: argument

--

if:

Using if: in your validation basically allows you to determine conditions on which the validator will fire. I see from the link, the guys are using if: :avatar_changed?

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.

I would do this:

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? }

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




回答2:


try this:

has_attached_file :attachment, :styles => { :small => "200x200>" }
validates_attachment :attachment,
    :size => { :in => 0..500.kiobytes },
    :content_type => { :content_type => /^image\/(jpeg|png|gif|tiff)$/ }

its working on my app. except i have set a default attachment in case user chooses not to upload one.



来源:https://stackoverflow.com/questions/24030256/validates-attachment-for-optional-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!