Rails Active Storage Tutorial

This tutorial will give you a basic idea on how to use Rails Active Storage
• Rails 5.2.0

We assume rails 5.2.0 is already install in your system, if not please find instruction here

Create App

rails new storage-app

Now let’s install Active Storage in our application.

This migration create two tables, called
– active_storage_blobs
– active_storage_attachments

Blob stores metadata such as filename and content-type.

Attachments stores record_id, blob_id and other ID’s as reference for our application.

You can find table schema in db/schema.rb

Model for attachment
Let’s assume we want to attach image to a blog post, we can do as per following.

rails g resource blog title:string content:text

don’t forget to run

rails db:migrate

to perform migration on the generated model

Attachment for Model
Go to App->Model->blog.rb
Then add

has_one_attached :image

it will look like this

Now let’s go to App->Controller->blogs_controller.rb then add following code below

Ofcourse, if we have controller we must have view.
Let’s go ahead and create that, go to App->Views->Blogs
Create new.html.erb and add code below

then Create show.html.erb


rails s

Open browser and go to http://localhost:3000/blogs/new

everything should work fine

Leave a reply:

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Site Footer