views:

395

answers:

2

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/

A: 

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

Andrew Nesbitt
It doesn't seem to work. After adding:validates_attachment_size :document, :less_than => 5.megabytes, :allow_nil => trueNotes won't save to the database at all. In my notes controller, I have an if statement saying if @note.save, do the good stuff, else redirect back to page with a flash error.It redirects every time - @note.save won't fire correctly. I have no other validations in notes that could be causing it to not save, since commenting out the paperclip validation makes everything work normal.
Steve
Logs don't detail anything specific to paperclip either (which is dissapointing).Update: Check out the following: http://github.com/thoughtbot/paperclip/issues/issue/134
Steve
A: 

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

Lin He