Published by Simon Schoeters

Multi size default images with paperclip

I needed some avatar images in a recent Ruby on Rails project. File uploading in Rails is never easy but the paperclip gem makes it so much easier.

Now, paperclip has a fallback method when an image is missing. Defining the default image saves you from writing duplicate tests in your views to handle the missing image cases. You can specify the default URL like this:

has_attached_file :avatar, :default_url => '/images/avatar_missing.png'

So far so good but what if you need a specific image for each avatar size? Not that hard either:

has_attached_file :avatar, :styles => {:small => '30x30#', :large => '100x100#'}, :default_url => 'missing_:style.png'

All you need is 2 images for the missing avatars, one small one of 30×30 pixels and another larger one of 100×100 pixels. Named missing_small.png and missing_large.png respectively.