1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails Active Storageを用いた画像投稿機能

1
Last updated at Posted at 2022-03-04

インストール

$ bundle install
Gemfile
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を使って画像アップロード機能の実装

投稿画面の作成

posts/new.html.erb
 <%=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でファイル選択ボックスを生成

参考記事

Railsドキュメント

コントローラの作成

posts_controller.rb
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の使い方

画像の表示

posts/show.html.erb
  <% if @post.image.attached? %>
<%=image_tag @post.image %>
          <% end %>

attached?メソッドで画像の添付をチェックします。
image_tagとは画像を表示するためのimgタグを作成するヘルパーメソッドです

参考記事

rails ActiveStorageを用いての画像投稿方法
【Rails】 image_tagを使って簡単に画像を表示させよう!

モデルファイルの作成

post.rb
class Post < ApplicationRecord
 has_one_attached :image
end

保存したいテーブルのレコードと画像を紐づけるためにhas_one_attachedというメソッドを利用します.
これは各レコードとファイルを1対1の関係で紐づけるメソッドです。
これによってPostモデルに一つの画像が紐づきます。

参考記事

rails ActiveStorageを用いての画像投稿方法
ファイルをレコードに添付する

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?