Steve
Steve

Reputation: 592

Rails Paperclip plugin - Validations

The rails plugin paperclip supports validations at the model such as:

validates_attachment_size

The only problem is that using this validation seems to force the validation of an actual attachment, where sometimes there may not be one.

If I'm validating the following, what condition :if could I use to ignore the validation if there is not :document present? (meaning the user submitted the parent object without a document attached).

validates_attachment_size :document, :less_than => 5.megabytes, :if => ???

The parent object is a :note, so in the note.rb file I have:

has_attached_file :document

RDocs: dev.thoughtbot.com/paperclip/

Upvotes: 1

Views: 1749

Answers (3)

digitalWestie
digitalWestie

Reputation: 2797

Check for a file name.

validates_attachment_size :document, :less_than => 5.megabytes, :if => !self.document_file_name.nil?

Upvotes: 0

he9lin
he9lin

Reputation: 53

You can pass in :if => lambda { avatar.dirty? } after the validation statement, assuming your attachment is named avatar. For example:

validates_attachment_size :avatar, :less_than => 500.kilobytes, :if => lambda { avatar.dirty? }

Upvotes: 2

Andrew Nesbitt
Andrew Nesbitt

Reputation: 6046

You can add the :allow_nil => true option which will skip the validation if the attachment isn't present.

Upvotes: 0

Related Questions