Integrating Cloudinary with Active Storage in Rails 6

Just about every application inevitably needs to support file uploads of some kind. For example, a user might need to associate a profile picture with their bio, or notes may be more helpful if attachments could be attached, etc. Cloudinary can be a great choice, as it’s quick and easy to implement, and handles a lot of the heavy lifting for us, including integration with various cloud storage providers.

Installation

We use the dot-env gem for storing API keys in our .env file. Install dot-env by adding it to your Gemfile:

1
2
gem "dotenv-rails"
gem "cloudinary"

Of course, run the command bundle install.

Add two files, .env and .env.sample in your project root and add .env in the .gitignore because we don’t want our secret keys to be visible in git or anywhere else.

Now let’s create a free Cloudinary account and get our API keys.

I assume at this step that you have already created a Cloudinary account and just need to grab the secret keys. So, here you can find your API keys.

Add this to your .env file.

1
2
3
CLOUD_NAME=yourcloudname
API_KEY=yourapikey
API_SECRET=yourapisecret

Of course, you need to replace these dummy keys with your original ones. Also, add dummy values to .env.sample so as to send this file to git.

1
2
3
CLOUD_NAME=dummycloudname
API_KEY=dummyapikey
API_SECRET=dummyapisecret

Now add cloudinary.yml file in config folder and make sure it is something like this.

1
2
3
4
5
6
7
8
9
10
11
development:
  cloud_name: <%= ENV['CLOUD_NAME'] %>
  api_key: <%= ENV['API_KEY'] %>
  api_secret: <%= ENV['API_SECRET'] %>

production:
  cloud_name: <%= ENV['CLOUD_NAME'] %>
  api_key: <%= ENV['API_KEY'] %>
  api_secret: <%= ENV['API_SECRET'] %>
  secure: true
  cdn_domain: true

Configure your config/storage.yml file with the following line.

1
2
cloudinary:
  service: Cloudinary

Tell ActiveStorage which service to use for image uploads by putting this line in development.rb file.

1
config.active_storage.service = :cloudinary

Make sure you have this line in your application.js file.

1
require("@rails/activestorage").start()

Now that the basic setup of Cloudinary is done, let’s move on to the implementation.

For our example, we’ve got a Profile object that we want to be able to an image to. So, add this to profile.rb:

1
has_one_attached :image

Add this to your _form.html.haml partial:

1
2
3
= f.input :name
= f.input :short_description, as: :text
= f.input :image, as: :file

Your view that displays the image (such as show.html.haml) needs to include the following code.

1
= image_tag @profile.image if @profile.image.attached?

Before running and testing, you need to export your environment variables:

1
2
3
export CLOUD_NAME=yourcloudname
export API_KEY=yourcloudname
export API_SECRET=yourcloudname

Cloudinary is now installed and configured.