Dead Simple Rails 5.2.0, builtin files uploader – ActiveStorage

Hi ruby folks,

It’s all new shining Rails 5.2.0 with shiny new features. The major feature of this release is its very own solution for file uploads handling(ActiveStorage), CarrierWave, Paperclip, Shrine are story of past now- though they are damn good at achieving what they are build for.

ActiveStorage a child of Basecamp 3, framework. Lets look at it to add it to your awesome rails app.

To create a db migration just run following commands in terminal,

​​​​rails active_storage:install

rails db:migrate

this will create two tables in under-laying db.

active_storage_attachments, active_storage_blobs

ActiveStorage works just like Attachinary from Cloudinary’s  this is just for uploading images to their storage while ActiveStorage can upload to almost any cloud storage.

These are the basics, lets dead-simply see it in action.

run a scaffolding for a model creation

rails g scaffold User name:string gender:string
# app/models/user.rb
class User < ApplicationRecord
  has_one_attached :avatar
end

Controller Changes – users_controller.rb

# app/controllers/users_controller.rb
def 
  params.require(:user).permit(:name, :gender, :avatar)
end

 

Views Changes – _form.html.erb add below code above submit button

<!-- app/views/users/_form.html.erb -->
class="field"> %= form.label :avatar %> %= form.file_field :avatar %>

Views Changes – show.html.erb

<!-- app/views/users/show.html.erb -->
<% if @user.avatar.attached? %>
<!-- @user.image.present? will always return true, use attached? to check presence -->
  <p>
    <strong>User Avatar:</strong><br>
    <%= image_tag @user.avatar %>
  </p>
<% end %>

 

Grrrrrr……. Wasn’t it DeadSimple?

We’ll DeadSimply look at #multiple images, #Handlind N+1 Problem later some day. Follow and share to keep update.

 

 

 

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s