Setting a default image when using Cloudinary and CarrierWave in Rails

Thoughts from the team
By    | November 19, 2015 | Ruby on Rails, Tips & Tricks,

Cloudinary lets you specify a default_image parameter when using the cl_image_tag, along with all of your transformations, to provide a fallback image if one has not been uploaded.  If, however, you are using CarrierWave, you’ll likely want to define your transformations and the fallback image just once in your Uploader class.

The Cloudinary docs give loads of detail on creating a version that DRYs up your transformations, but doesn’t mention how to specify the default_image.  After digging around in the source of Cloudinary::CarrierWave I found two methods #default_public_id and #default_url that you can define in your Uploader to provide the fallbacks.

From #default_public_id you should return the public id of an already uploaded image, e.g. ‘avatar’.

The #default_url method lets you specify a URL to use, skipping Cloudinary completely, so you could use an asset in your project.

The final point to note is that when you use the image in the view you must call #url on your version, else the defaults do not get used.

Example

class Client::HeadshotUploader < CarrierWave::Uploader::Base
 include Cloudinary::CarrierWave

 version :circle do
   cloudinary_transformation format: :png, transformation: [
     {effect: :improve},
     {width: 300, height: 300, crop: :thumb, gravity: :face, radius: :max}
   ]
 end

 def default_public_id
   'headshot'
 end
end

and then in your view

<%= cl_image_tag client.headshot.circle.url %>

More like this