インストール
$ bundle install
gem 'mini_magick'
gem 'image_processing', '~> 1.2'
% rails active_storage:install
% rails db:migrate
MiniMagickはImageMagickをrailsで扱えるようにしてくれるGem
ImageProcessingはMiniMagickで提供できない画像サイズを調整する機能です。
Active Storageは、ファイルアップロードを行うための機能でこれを使えば、フォームで画像の投稿機能が作れます。
参考記事
【Rails 5.2】 Active Storageの使い方
RailsのActive Storageを使って画像アップロード機能の実装
投稿画面の作成
<%=form_with(model: @post, url: posts_path, local: true) do |f| %>
<h1>投稿する</h1>
<textarea name="content"><%= @post.content %></textarea>
<%= f.file_field :image %>
<input type="submit" value="投稿">
<% end %>
file_fieldでファイル選択ボックスを生成
参考記事
コントローラの作成
def create
@post = Post.new(
content: params[:content],
user_id: @current_user.id
)
if image = params[:post][:image]
@post.image.attach(image)
end
if @post.save
flash[:notice] = '投稿を作成しました!'
redirect_to('/posts/index')
else
render('posts/new')
end
end
@post.image.attach(image)で画像の添付を行います。
参考記事
【Rails 5.2】 Active Storageの使い方
画像の表示
<% if @post.image.attached? %>
<%=image_tag @post.image %>
<% end %>
attached?メソッドで画像の添付をチェックします。
image_tagとは画像を表示するためのimgタグを作成するヘルパーメソッドです
参考記事
rails ActiveStorageを用いての画像投稿方法
【Rails】 image_tagを使って簡単に画像を表示させよう!
モデルファイルの作成
class Post < ApplicationRecord
has_one_attached :image
end
保存したいテーブルのレコードと画像を紐づけるためにhas_one_attachedというメソッドを利用します.
これは各レコードとファイルを1対1の関係で紐づけるメソッドです。
これによってPostモデルに一つの画像が紐づきます。