This tutorial will give you a basic idea on how to use Rails Active Storage
Requirements:
• 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.
1 2 |
rails active_storage:install:migrations rails db:migrate |
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
1 2 3 |
class Blog < ApplicationRecord has_one_attached :image end |
Now let’s go to App->Controller->blogs_controller.rb then add following code below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class BlogsController < ApplicationController def new @blog = Blog.new end def create @blog = Blog.create! params.require(:blog).permit(:title, :content) @blog.image.attach(params[:blog][:image]) redirect_to @blog end def show @blog = Blog.find(params[:id]) end end |
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
1 2 3 4 5 6 |
<%= form_with model: @blog, local: true do |form| %> Title: <%= form.text_field :title %><br><br> Content: <%= form.text_area :content %><br><br> Image: <%= form.file_field :image %><br> <%= form.submit %> <% end %> |
then Create show.html.erb
1 |
<%= image_tag @blog.image %> |
run
rails s
Open browser and go to http://localhost:3000/blogs/new
everything should work fine