How to implement image posting function using Active Storage in Ruby on Rails

I think there are many ways to implement the image posting function in Ruby on Rails. In this article, I am a programming beginner who wants to change jobs as an engineer from inexperienced, and I have summarized the implementation method using Active Storage, which is probably the most common method.

Active Storage and ImageMagick

The image posting function this time has a function to upload an image and a function to process the image (change the size and save format).

The former is implemented using Active Storage and the latter using ImageMagick.

What is Active Storage?

It is a gem that can easily implement the file upload function added in Rails5.2. Originally it was a gem that needed to be installed, but it seems that it was integrated into Rails.

What is ImageMagick?

Software that allows you to add image processing from the command line. Introduce a gem called MiniMagick to use this software with Rails. You can also implement a function to adjust the image size by introducing a gem called Image Processing.

gem function
MiniMagick Make ImageMagick features available in Rails
ImageProcessing Provides a function to adjust the image size that MiniMagick cannot provide

I've introduced a few, but this article deals only with Active Storage. I would like to summarize MiniMagick and Image Processing by adding it to this article or writing it in another article in the future.

Ready to use Active Storage

On the terminal, move to the directory of the application you want to implement the image posting function, and enter the following command.

Terminal


rails active_storage:install
rails db:migrate

Since Active Storage is installed by rails active_storage: install and a migration file is also generated, it is migrated by rails db: migrate.

This migration will generate two tables named active_storage_blobs and active_storage_attachments. I've quoted an easy-to-understand article explaining these tables.

These tables are used by two models, Blob and Attachment. The Blob is a model that holds metadata such as file name, file type, number of bytes, error detection code, and the Attachment model is an intermediate table for associating a Blob object with an Active Record object. Note that you don't have to touch the Blob and Attachment models directly when using Active Storage. From Qiita [Rails 5.2] How to use Active Storage

By the way, the migration file generated by rails active_storage: install is as follows.

2020XXXXXXXXXX_create_active_storage_tables.active_storage.rb


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

You can see that the active_storage_blobs and active_storage_attachments tables have been created.

Allows you to save images

Implement to save the image in the Active Storage table created earlier.

There are two things to do: Here, let's assume that the table where you want to save the image is the Posts table (model is post.rb) and the controller is posts_controller.rb.

  1. Define associations between Active Storage tables and Posts tables
  2. Allow posting of image column in posts_controller.rb

Implement these in order.

1. Define associations between Active Storage tables and Posts tables

Use the has_one_attached method to define the association.

Method name function
has_one_attached Associate each record and file in a one-to-one relationship. has_one_One file can be attached to each record of the model that describes the attached method.

Write the has_one_attached method in post.rb as follows.

post.rb


class Post < ApplicationRecord
  has_one_attached :image
end

The : image part represents the file name, and it can be another file name such as: photo.

This description will allow you to access the attached file with model.filename (eg Post.image).

In addition, this filename will also be the key for the parameters sent by the form associated with the model.

2. Allow posting of image column in posts_controller.rb

Describe as follows.

posts_controller.rb


class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.create(post_params)
    redirect_to root_path
  end
  
  priveate
  def post_params
    params.require(:post).permit(:image)
  end
end

The private method post_params uses commit to allow the: image key to be saved. By the way, the post page is described as follows.

new.html.erb


<%= form_with model: @post, local: true  do |form| %>
  <%= form.file_field :image %>
  <%= form.submit %>
<% end %>

This completes the implementation of the image posting function. As a process after this, there is an implementation of the function to display the posted image, but I will omit it this time.

Reference material

Rails Guide v6.0 Active Storage Overview (https://railsguides.jp/active_storage_overview.html#disk%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9) ImageMagick Official Site MiniMagick Official GitHub Image Processing Official GitHub Qiita [Rails 5.2] How to use Active Storage

Recommended Posts

How to implement image posting function using Active Storage in Ruby on Rails
How to implement image posting using rails
[rails6.0.0] How to save images using Active Storage in wizard format
[Ruby on Rails] I want to get the URL of the image saved in Active Storage
Flow to implement image posting function using ActiveStorage
[Ruby on Rails] How to install Bootstrap in Rails
How to create a query using variables in GraphQL [Using Ruby on Rails]
How to implement gem "summer note" in wysiwyg editor in Ruby on Rails
[Rails] Implement image posting function
Continued ・ Flow to implement image posting function using ActiveStorage
[Ruby on Rails] How to write enum in Japanese
[Ruby On Rails] How to reset DB in Heroku
[Ruby on Rails] Post image preview function in refile
Rails learning How to implement search function using ActiveModel
How to use Ruby on Rails
[Rails] How to use Active Storage
How to display a graph in Ruby on Rails (LazyHighChart)
[Ruby on Rails] How to implement tagging / incremental search function for posts (without gem)
How to implement a circular profile image in Rails using CarrierWave and R Magick
How to implement search functionality in Rails
[Ruby on Rails] How to use CarrierWave
[Ruby on Rails] Image slideshow using Skippr
[Ruby on Rails] How to use redirect_to
How to implement ranking functionality in Rails
[Ruby on Rails] How to use kaminari
How to implement UI automated test using image comparison in Selenium
How to implement a slideshow using slick in Rails (one by one & multiple by one)
How to build a Ruby on Rails environment using Docker (for Docker beginners)
How to debug the processing in the Ruby on Rails model only on the console
[Ruby On Rails] How to search the contents of params using include?
[Ruby on Rails] How to display error messages
How to add / remove Ruby on Rails columns
Implement star rating function using Raty in Rails6
How to implement the breadcrumb function using gretel
How to implement a like feature in Rails
[Rails] Show avatars in posts using Active Storage
How to link images using FactoryBot Active Storage
How to make a follow function in Rails
[Ruby on Rails] How to use session method
How to implement Pagination in GraphQL (for ruby)
[Ruby on Rails] How to log in with only your name and password using the gem devise
[Ruby on Rails] When logging in for the first time ・ How to split the screen in half using jQuery
How to resolve errors that occur in the "Ruby on Rails" integration test
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
[Ruby on Rails] Asynchronous communication of posting function, ajax
How to implement guest login in 5 minutes in rails portfolio
How to implement a like feature in Ajax in Rails
[Implementation procedure] Implement image upload function with Active Storage
[Ruby on Rails] How to change the column name
[Ruby on Rails] Posting score ranking function (whole display)
[Rails 6] How to set a background image in Rails [CSS]
[Rails 6] Add images to seed files (using Active Storage)
(Ruby on Rails6) How to create models and tables
[Rails] How to display an image in the view
Try to implement tagging function using rails and js
Implement application function in Rails
Implement follow function in Rails
[Rails] How to implement scraping
Ruby on Rails Email automatic sending function setting (using gmail)
How to deploy jQuery in your Rails app using Webpacker
[Ruby on Rails] Implement login function by add_token_to_users with API