[RUBY] Rails Active_storage -Simplify saving images-

What is Active storage Active Storage is a function for uploading files. If you use this, you can easily create an image posting function etc. with a form. You can easily upload files to cloud storage services (Amazon S3, Google Cloud Storage, Microsoft Azure Storage, etc.).

Introduction method
  • Create a table along Active_storage
% rails active_storage:install

Install Active_storage and generate related files (migration, etc.)

%rails db:migrate

If you check Seaquel Pro and the following table is generated, it is successful so far. image.png This completes the "container" for storing images.

Model description: Attach one image Image information such as "attach an image to a message" or "attach an image to a product information" is often related to other models. A common idea here is to create an image model and make an association because there is an images table. Actually, there is no need to create a separate model for the table created by active_storage. Add "has_one_attached: file name" to the model you want to be involved in and the association will be completed. This time, we will assume that you will form an association with the message. models/message.rb
class Message < ApplicationRecord
  ~Descriptions such as other associations are omitted~

  has_one_attached :image
 
end

It may be easier to imagine saying "I made a pseudo image column" rather than an association.

Controller description: Strong parameters

Looking at the message table of seaquel_pro, the image column does not exist image.png

However, due to has_one_attached described in the model, there is a "pseudo image column" in the messages table.

  • Image information is saved in the table generated by rails active_storage: install.

From this, the image information can be skipped in params in messages_controller.rb.

controllers/messages_controller.rb

class MessagesController < ApplicationController

  def new
    @message = Message.new
  end

  def create
   @mesage = Message.create(message_params)
  end

  private

  def message_params
      params.require(:message).permit(:content, :image).merge(user_id: current_user.id)
  end
end

View description: Send image For this, use the form element file_field as usual.
<%= form_with model: @message, local: true  do |form| %>
  <%= form.text_area :content %><br>
  <%= form.file_field :image %><br>
  <%= form.submit %>
<% end %>

View description: Image display You can also use the img tag, but use the rails helper method image_tag to simplify the description.
<% if @message.image.attached? %>
  <%= image_tag @message.image %>
<% end %>

that's all! !!

Recommended Posts

Rails Active_storage -Simplify saving images-
Use images in Rails
[rails] How to post images
[Rails] Upload videos with Rails (ActiveStorage)
[Rails] Save images using carrierwave
Rails6 OmniAuth activestorage Get user image