知易行难

Developer in love with Ruby/Rails/Cocoa

Paperclip Validation

07 Dec 2008

The most common work I need to do right after creating a Photo model using attachment_fu is to add constraints on the file types (content type) and sizes:

has_attachment  :storage => :file_system,
                :content_type => :image,
                :max_size => 300.kilobytes
                ...

Paperclip does this in a similar way but instead of passing options to has_attached_file, it provides another two class methods:

has_attached_file :avatar,
    :styles => { :medium => "200x200>", :thumb => "100x100>" }

validates_attachment_content_type :avatar,
    :content_type => ['image/jpg', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png'],
    :message => "only image files are allowed"

validates_attachment_size :avatar,
    :less_than => 1.megabyte, #another option is :greater_than
    :message => "max size is 1M"

Both are very sweet.