Uploading Files Into Ruby On Rails ActiveStorage

Tram Ho

Preamble

When storing files in Rails, the first toolkit that we approach is 3rd party gems such as CarrierWave or Paperclip (before not being used as a replacement for Active Storage). Active Storage was introduced with Rails 5.2.

Active Storage facilitates the upload of files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage, and attaches those files to Active Record objects. It comes with a local disk-based service for development and testing, and supports file replication to subordinate services for backup and migration.

Using Active Storage, an application can convert image uploads with ImageMagick, create image presentations of non-image uploads like PDFs and videos, and extract metadata from arbitrary file.

Perform

Go to the terminal and create a new rails application

rails new app

Create an application, create a simple blog app with the scaffold command.

rails g scaffold Post title: string content: text

After the process is completed, run the migrate

rails db: migrate

Then enter custom routes

Now we will add an image to our post. First we need to install active storage on our posts.

rails active_storage: install

After running this command, Rails will generate a migration file for you. When testing, you will see two different tables: active_storage_blobs and active_storage_attachments.

Then we run the migrate file

rails db: migrate

Next we add the following model:

Again, we will need to add the image to our controller at the end of the post_params method, adding the image to the modle properties.

In app / view / posts / _form.html.erb, we will edit the file by adding input to the image.

Now we need to load the images in the index and show

Now it is possible to post images in a post, but now we want to use the gem active_storage_validations when we need to post an image. We add the gem “active_storage_validations” into the gem file and bundle install. Later :

With the above validation we only accept images with png, jpg and jpeg extensions attached to it when creating a post must have photos attached when creating a post. So we can post with the image file attached.

Reference source:

https://hackernoon.com/uploading-files-into-ruby-on-rails-activestorage-gv1r3ukr

Share the news now

Source : Viblo