📸Images & media

Image Processing and Storage with Cloudinary

Welcome to the Image Processing and Storage section of our wiki! In this guide, we will explore how to efficiently handle image management within our application using Cloudinary.

Cloudinary is a powerful cloud-based service that provides an extensive suite of tools for image upload, storage, and manipulation. It allows developers to easily integrate image processing capabilities into their applications, making it simple to transform, resize, and optimize images on-the-fly. And the best part is it has a very generous free plan as the free credits renew monthly 🎉

By leveraging Cloudinary, we can enhance our application's performance and improve the user experience through faster image delivery and efficient management. Let's get started!

Setting up Cloudinary in Your Application

To get started with Cloudinary, you need to create an account on their website, find your API key, and add it to your .env file in your LightningRails application.

# .env
CLOUDINARY_URL=cloudinary://298522699261255:***********************8@Qa1ZfO4syfbOC # Your Key

Installing Active Records

Active Storage enables the upload of files to cloud storage services, such as Cloudinary, and allows you to link these files to Active Record models.

rails active_storage:install
rails db:migrate

This sets up two database tables to manage the relationships between files uploaded to Cloudinary and any model within our application.

Attaching Images to Your Models

Once Cloudinary is set up, you can easily attach images to your models using Active Storage or another file attachment library. This section will cover how to associate image uploads with your database models, ensuring that your images are properly linked and accessible.

Setup for one image

# models/car.rb
class Car < ApplicationRecord
  has_one_attached :photo
end

In your controller:

# app/controllers/cars_controller.rb
def car_params
  params.require(:car).permit(:title, :photo)
end

In your view:

<!-- app/views/cars/_form.html.erb -->
<%= simple_form_for(car) do |f| %>
  <!-- [...] -->
  <%= f.input :photo, as: :file %>
  <!-- [...] -->
<% end %>

Setup for multiple images

# models/car.rb
class Car < ApplicationRecord
  has_many_attached :photos
end

In your controller:

# app/controllers/cars_controller.rb
def article_params
  params.require(:car).permit(:title, photos: [])
end

In your view:

<!-- app/views/cars/_form.html.erb -->
<%= simple_form_for(car) do |f| %>
  <!-- [...] -->
  <%= f.input :photos, as: :file, input_html: { multiple: true } %>
  <!-- [...] -->
<% end %>

Displaying the image in the view

To display the image on your view, we will need to change the image_tag by cl_image_tag and call its key:

<%= cl_image_tag @car.photo.key, height: 500, width: 500, crop: :fill %>

Et voila! 🥖 You have a free cloud provider for your rails images.

Last updated