Ruby IV | Image Upload 🖼️

Milan Parmar
3 min readJan 10, 2021

--

Welcome to the fourth instalment in my Ruby series…Image upload!

This explanation is for Ruby on Rails and I’ll be using examples from my Rails Flatiron project — Reflections, to show you how it’s done. The way we achieve image upload is by using a gem called active storage.

Active Storage

Active Storage allows the functionality of uploading files to a cloud storage service and attaching those files to Active Record objects. However, when in the testing and development phase, we can use our local-disk to store the image uploads (note that non-image uploads such as documents and videos are also possible). The great thing is that active storage is included in Rails 5.2+.

Install Active Storage

First things first, we need to install Active Storage by running the following:

rails active_storage:install

This would then copy a migration file into the db/migrate directory containing two tables:

# This migration comes from active_storage (originally 20170806125915)
class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
def change
create_table :active_storage_blobs do |t|
t.string :key, null: false
t.string :filename, null: false
t.string :content_type
t.text :metadata
t.bigint :byte_size, null: false
t.string :checksum, null: false
t.datetime :created_at, null: false
t.index [ :key ], unique: true
end
create_table :active_storage_attachments do |t|
t.string :name, null: false
t.references :record, null: false, polymorphic: true, index: false
t.references :blob, null: false
t.datetime :created_at, null: false t.index [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
end
end

The beauty of active storage is that you will not need to add an Images model or add an images attribute directly to the respective migration table. It will already handle that for you! 😁

Next you want to run rails db:migrate.

As mentioned above, when in the development or testing phase of your application, built-in disk storage is a good place to store upload files. To use disk storage, you will need to include this piece of code in your storage.yml file (usually in your config folder):

test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
local:
service: Disk
root: <%= Rails.root.join("storage") %>

To use tests, we need to go to config > environments > test.rb and make sure this piece of code exists in there:

config.active_storage.service = :test

Reflections — Rails Web App

Reflections is a web application that allows users to create an account, upload their favourite books and write reflections on those books. They can also view other users’ profiles and see their reflections. I’ll be using examples from Reflections for the next few steps.

Declaring Attachments Associations

So I wanted to create the functionality where users can upload images for a book and in order to achieve this, I added a declaration in the book model:

has_one_attached :image

Note that the name, image, doesn’t match any database column name, so you can name the attachment however you like. In my case, I just named it image as users would be uploading…an image 👀…for a book.

Image Upload

Now that the book model was ready to accept an image attachment, I created a form which included a file upload input field:

<div class="upload-button"><%= f.file_field :image %></div>

This is how it looks like on my form:

Reflections — Book form

We need to also add :image to our strong params in the book controller.

params.require(:book).permit(:title, :author, :image)

Displaying an uploaded image

In order to display the image, on my show page, I needed to do the following:

<img src="<%=(url_for(@book.image))%>">

And voila! Image successfully uploaded and displayed! 🎉

Make sure you buy this book…Jay is great!

Now you know how to upload images to your Rails application, have fun and make sure you read up on how to upload images/documents to cloud storage services here!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Milan Parmar
Milan Parmar

Written by Milan Parmar

Software Engineer 👨🏽‍💻 | Full Stack Web Development 💻 | Smartphone Tech Enthusiast📱

No responses yet

Write a response