Rails Paperclip Plugin Validation If No Attachment Present

On a martial arts marketing website, Through the Ranks, I use ThoughtBot’s excellent file upload plugin, Paperclip, the defacto standard for managing Rails file uploads.

However, one problem has been vexing me since day one. And that is validating only when an attachment exists. For example, in my Rails application, I give users the option of uploading a logo and other photos. But they don’t always upload one. However, when they DO, I need to validate they aren’t injecting something nasty (javascript, for example) or huge .bmp image files into my database.

So…how do you do that? How do you validate a Paperclip attachment if – and only if – an attachment exists?

Some people say to add the old…

  :allow_nil => true  

option in the model that has paperclip attachments.

But that does NOT skip the validation if the attachment isn’t present. This simply allows you to submit a form with no attachment present. It does NOT skip your validation if your attachment object does not exist. So…here’s a nice snippet of code that allows you to skip validation if no attachment is present. Here’s all you do:

Paperclip: How to Skip Validation When No Attachment Exists

  1. Open /vendor/plugins/paperclip/lib/paperclip.rb
  2. Comment out the following code (or delete it):

    
        #      validates_inclusion_of :"#{name}_file_size",
        #                             :in      => range,
        #                             :message => message,
        #                             :if      => options[:if],
        #                             :unless  => options[:unless]
    
      

  3. Add the following in its place:

           validates_inclusion_of :"#{name}_file_size",
                                 options.merge(:in => range, :message => message)
        

  4. Now restart your server. Your Paperclip validation headache is now gone!

4 FEEDBACKS

  1. Picard says:

    Hi,
    i had the same issue few days ago.
    My solution looks like this:

    validates_attachment_presence :file unless :file
    validates_attachment_content_type :file, :content_type => [‘image/jpeg’, ‘image/jpg’, ‘image/gif’, ‘image/png’, ‘image/bmp’] unless :file

    It works fine for me 😉

    Greets, Picard

  2. Chris Whamond says:

    Nice – that’s a good approach, too. Thanks Picard.

  3. he9lin says:

    The following has worked for me:

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

    dirty? returns true for the attachment if it is reassigned.

  4. Rooby G says:

    I updated the sample code above slightly. When I perform ‘Person.new.valid?’ the result is false. I’m running Rails 2.3.8 and Paperclip 2.2.15

LEAVE A COMMENT