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.
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