2023-05-26 - Cloudinary and Heroku
main topics
- Deploy to Heroku
- Image Upload to Cloudinary
Cloudinary
Starts at 27 minutes.
First of all: Create an account at https://cloudinary.com/.
Gemfile
:
gem 'cloudinary'
gem 'dotenv-rails', groups: %i[development test]
bundle install
touch .env
echo '.env*' >> .gitignore
.env
CLOUDINARY_URL=cloudinary://<api_token_here>
Around 38 minutes, examples of cl_image_tag
.
Active Storage
At 42 minutes starts talking about ActiveStorage
rails active_storage:install
rails db:migrate
configure config/storage.yml
cloudinary:
service: Cloudinary
configure config/environments/development.rb
(replacing :local
with :cloudinary
:
config.active_storage.service = :cloudinary
In the model you want to have a photo:
class MyModel < ApplicationRecord
has_one_attached :photo
# if you want multiple attached images...
has_many_attached :photos
end
In your form, add something like this:
f.input :photo, as: :file
# full multiple photos
f.input :photos, as: :file, input_html: { multiple: true }
- permit
:photo
in the controller (strong params)- multiple:
.permit(..., photos: [])
(yeah, empty array)
- multiple:
Display an image from Cloudinary
Use cl_image_tag
in the view:
cl_image_tag @article.photo.key
# if multiple photos, iterate over
# the @article.photos array
54 minutes: Usage in background-image:
<div
class="card-category"
style="
background-image:
linear-gradient(rgba(0,0,0,0.3),
rgba(0,0,0,0.3)),
url('<%=
cl_image_path
@article.photo.key,
height: 300,
crop: :fill
%>')"
>
Cool article
</div>
Seeding images
Use #attach
method (in the example below it's article.photo.attach
):
require "open-uri"
file = URI.open("https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/NES-Console-Set.jpg/1200px-NES-Console-Set.jpg")
article = Article.new(title: "NES", body: "A great console")
article.photo.attach(io: file, filename: "nes.png", content_type: "image/png")
article.save
Helpful Active Storage methods:
@article.photo.attached?
@article.photo.purge
At 1:03:00 starts the explanation about multiple images upload.
Around 1:08:00 there's an explanation about Active Storage DataBase stuff, and I think it's not well explained.
Deploy to prod
config/environments/production.rb
:
config.active_storage.service = :cloudinary
heroku config:set CLOUDINARY_URL=cloudinary://hashDoidão...
# checking
heroku config
Heroku
Installation
Create new app
heroku create $APP_NAME --region us
# just checking:
git remote -v
# should show a heroku repo
# remember: create an Add-on for the Postgres DB
# deploy to heroku:
git push heroku master
# don't forget to run the migrations, etc...
heroku run rails db:migrate
heroku run rails db:seed
# check the logs
heroku logs --tail