With Active Storage, you can use methods that make it easy to upload files such as images, and you can easily create tables to store images.
First, we will introduce the image conversion tool required for image processing and the gem to make it available from Rails. ImageMagic allows you to create, resize, and change the save format of images from the command line. Execute the following command.
brew install imagemagick
ImageMagic is not a gem, so to handle it with Ruby or Rails, you need to install a gem called MiniMagick. MiniMagic is a gem that allows ImageMagic to be used in Ruby. Next, install the gem to change the image size. Image Processing is a gem that provides a function to adjust the image size, which is not possible with MiniMagic. Add it to the bottom of the gemfile as follows. Then run bundle install with the command.
gemfile
gem 'mini_magick'
gem 'image_processing', '~> 1.2'
Do the following in your terminal:
rails active_storage:install
Now that the migration related to Active Storage is created, do the following:
rails db:migrate
Set the association definition and save permission for the image column to store images in Active Storage tables. This time, I used the has_one_attached method to attach one image file.
app/models/post.rb
class Post < ApplicationRecord
~Abbreviation~
has_one_attached :image
~Abbreviation~
end
The image file is now linked to the posts table. ** At this time, you don't need to add any columns to the posts table. ** **
Then add an image to the strong parameter to allow the image file to be saved.
app/controllers/posts_controller.rb
class PostsController < ApplicationController
~Abbreviation~
def post_params
params.require(:post).permit(:name, :image, :price, :evaluation, :description, :category_id, :shop_name).merge(user_id: current_user.id)
end
~Abbreviation~
end
Display the image using the image_tag method, which is a Rails helper method.
<%= image_tag post.image, class: "post-img" %>
You can use the attached? method to prevent errors when the image does not exist.
<%= image_tag @post.image ,class:"user-box-img" if @post.image.attached? %>
By writing as above, image_tag will be loaded only when the image exists.
If you have Active Storage installed, you can use the variant method. You can specify the display size of the image file by using the variant method.
<%= image_tag post.image.variant(resize: '500x500'), class: "post-img" %>
Recommended Posts