1

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.

Community
  • 1
  • 1
John
  • 6,404
  • 14
  • 54
  • 106

2 Answers2

2

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

Richard Peck
  • 76,116
  • 9
  • 93
  • 147
0

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.

BallsOfSteel
  • 126
  • 9