Active Storage can be useful for integrating image uploads with your model. The Cloudinary gem enables you to enjoy the benefits of Active Storage for easily uploading images from HTML forms to your model, while enjoying the great benefits of Cloudinary: uploaded images are stored in the cloud, transformed in the cloud, and delivered automatically through a CDN.
The following documentation assumes you have already set up Active Storage within your Rails 6+ application, and teaches you how to configure Active Storage to work with Cloudinary for image uploads and image delivery.
Declare the Cloudinary service in the
config/storage.yml file by adding a new entry with a custom name (e.g., cloudinary) and the service configuration:
cloudinary: service: Cloudinary # Any other settings you want, to be sent on all requests, can be included here as well.
Tell Active Storage which service to use by setting
Rails.application.config.active_storage.service. As each environment will likely use a different service, it is recommended to do this on a per-environment basis. For example, to use the
cloudinary service in the development environment, you would add the following to
Active Storage already supports uploading directly from the client to the cloud. After adding Cloudinary as a service, use direct uploading as usual:
Using the asset pipeline:
Using the npm package:
Annotate file inputs with the direct upload URL.
- As an upload preset (or upload parameters) in the Rails service configuration (as top-level parameters)
- As a default upload preset specified via the console which will be applied to all uploads without any extra code on the Rails side
Use the cl_image_tag method to generate an HTML image tag, or use the cloudinary_url method to generate a transformation URL. The methods can accept any Cloudinary Transformation URL API Reference for lazily transforming the image on delivery (as per all Cloudinary dynamic URLs). For example, to deliver a user's avatar image scaled down to 300x200 with the 'cartoonify' effect applied:
<%= cl_image_tag(@user.avatar.key, width: 300, height: 200, crop: :scale, effect: "cartoonify") %>
<%= cloudinary_url(@user.avatar.key, width: 300, height: 200, crop: :scale, effect: "cartoonify") %>
variantmethod should not be used as it would try to create a new resource and upload it to Cloudinary, instead of letting Cloudinary handle the transformation. As such, the
variantmethod is not needed or supported.