[RUBY] Use ActiveStorage!

I thought I had to spend some time on the output, but I didn't do it, so I thought I should lift my waist ... Do you use it every time this time? I'm looking back, so I'll write down what I'm using here.

Overview

--What is Active Storage? --Introduction method

What is Active Storage?

What is Active Storage? It provides the ability to upload files to cloud storage services such as Amazon S3, Google Cloud Storage, and Microsoft Azure Storage, and attach files to Active Record objects. Local disk-based services for development and test environments are available, and files can also be mirrored to lower-level services for backup and migration.

With Active Storage in your application, you can use ImageMagick to convert image uploads, generate non-image upload image representations such as PDFs and videos, and extract metadata from arbitrary files.

Rails Guide Quote

It is a Gem that can easily implement the image upload function. Active Storage is included as standard from Rails 5.2.

Introduction method

--Prepare an Active Record model First, in the directory of the application you want to install

rails active_storage:install

Running the rails active_storage: install command creates a migration related to Active Storage. Continue to migrate.

rails db:migrate

The following two tables are generated. One of the features of Active Storage is that there is no need to prepare columns for images.

active_storage_blobs

Column name Saved contents
id ID
key Key that uniquely identifies the file
filename The name of the uploaded file
content_type File type
metadata Metadata(If it is an image, the vertical and horizontal sizes are stored.)
byte_size file size(byte unit)
checksum Checksum
created_at Creation date and time

active_storage_attachments

Column name Saved contents
id ID
name Model attribute name(User model avatar)
record_type Model name(User)
record_id record_model ID of type
blob_id active_storage_blogs ID
created_at Creation date and time

how to use

** Use the post table as an example. ** **

What to do

--Define Active Storage and post table associations --Allow to save image column in post_controller.rb

Use has_one_attached to attach a single image to your model.

class model< ApplicationRecord
  has_one_attached :file name
end

has_one_attached method

This method links each record and file in a one-to-one relationship. Each record in the model that describes the has_one_attached method can have one file attached to it. has_one_attached: The file name is Specify whatever you like, such as: photo,: avatar,: hoge, etc., according to the purpose of the file.

Strong parameters that allow image storage

  private

  def post_params
    params.require(:post).permit(:image).merge(user_id: current_user.id)
  end

Omitted about strong parameters You have now allowed the image to be saved.

View saved image

--image_tag method

A Rails helper method that creates an img element.

In the image_tag method, even if you do not specify a complicated Rails directory path, just call the image file from the model and describe it in the argument to generate an img element that displays the image. That is easy.

#When specifying a file from the model
<%= image_tag model.Image file%>
<%= image_tag user.avatar %>

# app/assets/You can also specify the image file path under the directory
<%= image_tag Image file path%>
<%= image_tag "avatar.png " %>

Self-talk (self-experience story and digression) I forgot the existence of image_tag and was trying hard to display the image w Even if I pulled it from the post model in this case, the image itself was in another table, so the display was only as follows.

#<ActiveStorage::Attached::One:0x00007f8ba7b765f8>

How do you have options?

 <%= image_tag post.image, class: 'post-image' if post.image.attached? %>

attached? method

A method that returns true or false depending on whether the record has a file attached.

model.file name.attached?

As a usage, since the description to display the image is always read, an error will occur if the image does not exist, so use this method By devising using an if statement, it is possible to read the description that reads the image only when the image exists. ** Class attributes can also be added.

About image processing tools

ImageMagick A tool that allows you to process images from the command line. Processing includes creating and resizing images, and changing the save format.

ImageMagick is software, not Gem. Therefore, install it from Homebrew.

To handle ImageMagick that is not a Gem in Ruby or Rails, you need a Gem called MiniMagick.

brew install imagemagick

There is no problem if you put this in once, so if it is in, you can skip it.

MiniMagick It is a Gem that makes it possible to handle the functions of ImageMagick in Ruby. You will need it to work with ImageMagick in Rails.

ImageProcessing It is a Gem that provides a function to adjust the image size, which MiniMagick cannot provide.

#Described at the bottom of the Gemfile

gem 'mini_magick'
gem 'image_processing', '~> 1.2'
 bundle install

I updated the gem, so don't forget to start the server.

If you implement this, you can specify the display size of the file by using the variant method.

model.file name.variant(resize: 'Width x height')

Impressions

I wrote it with the intention of keeping it as a record. Last but not least, please comment if there are any improvements in writing skills or communication. I'm sorry if there are any other mistakes in the description. Please point out. In addition to this, I often see how to use S3, but after actually trying this, I think I will leave it as an additional note. Thank you for your cooperation.

Reference URL

https://qiita.com/hmmrjn/items/7cc5e5348755c517458a https://qiita.com/kimuray/items/3335a87d3488be340374 https://qiita.com/sibakenY/items/e550166970e84d96e16e https://railsguides.jp/active_storage_overview.html#active-storage%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6

Recommended Posts

Use ActiveStorage!
Use before_action! !!
Use XMLHttpRequest
Use AutosizingTextView
Use JavaFX / TextFormatter
ActiveStorage vs CarrierWave
Use ControlsFX / Validation
Let's use jcmd
[Java] Use Collectors.collectingAndThen
[Rails] Use jQuery
Use sassc directly