Image posting function

Introduction

When creating the original application, we implemented a function to post images, so I will post it so that I will not forget it. There were various methods when I looked it up with Qiita etc., but this time I used a function called Active Storage of Rails.

1. Introduction of Active Storage and image processing tools

  1. Install ImageMagic in the terminal

Terminal

% brew install imagemagick

2. Write the Gem of mini_magick and image_processing in the Gemfile and bundle install

Gemfile


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

3. When you install Active Storage in the terminal, a migration will be created, so migrate it.

Terminal

rails active_storage:install

Terminal

rails db:migrate

2. Save the image

This time we will implement it assuming that it will be entwined with the Post table

  1. Associate the Active Storage table and Post table using the has_one_attached method

Post model


class Post < ApplicationRecord
  has_one_attached :image
end

2. Add image to Post's strong parameter so that it can be saved

Post controller


#Omission
  private
  def post_params
    params.require(:post).permit(:hoge, :fuga, :image)
  end

3. Image display

Display an image using the image_tag method

Post view


#Omission
  <div class='post'>
    <%= image_tag post.image, class: 'post-image' %>
  </div>

Recommended Posts

Image posting function
[Rails] Implement image posting function
Image preview function
Image preview function implementation
Flow to implement image posting function using ActiveStorage
Continued ・ Flow to implement image posting function using ActiveStorage
Implementation of image preview function
[Rails] Implementation of image preview function
[Rails] Voice posting function ~ Cloudinary, CarrierWave
Add pdf file posting function with carrierwave
[Rails] Image posting by CarrierWave [AWS EC2]
Allow image posting with [Docker + WordPress + MySQL]
Login function
Image upload
How to implement image posting using rails
JavaScript function
SpringMVC-Interceptor function
Multiple image upload function using Rails Carrierwave
How to implement image posting function using Active Storage in Ruby on Rails
[Rails] Implementation of image enlargement function using lightbox2
Posting function implemented by asynchronous communication in Rails