LoginSignup
10
6

More than 1 year has passed since last update.

【Rails】複数画像投稿機能の導入

Posted at

目的

Railsで作成したアプリに複数画像投稿機能を導入する。

開発環境

macOS: Big Sur
Rubyバージョン: 2.6.5
Railsバージョン: 6.0.0

前提

手順

  1. はじめに
  2. アソシエーションの設定
  3. ストロングパラメーターの定義
  4. 画像投稿ページの編集
  5. 画像表示ページの編集

はじめに

今回は複数画像投稿機能を実装していきます!

アソシエーションの設定

まずはアソシエーションの設定です。
現在、1対1で紐づいている関係を1対多に設定します。

app/models/post.rb
class Post < ApplicationRecord
  has_many_attached :image
end

has_many_attachedメソッドとは、各レコードとファイルを1対多の関係で紐づけるメソッドです。

ストロングパラメーターの定義

次にストロングパラメーターの定義です。
送られてくるパラメーターは配列に格納されているため、ストロングパラメーターも配列形式にします!

app/controllers/posts_controller.rb
  # 中略

  private

  def test_params
    params.require(:post).permit(:text, image: [])
  end
end

画像投稿ページの編集

複数枚画像投稿の場合は「multiple: true」を追記することによって、複数枚画像を選択することができます。

_form.html.erb
<div class="field">
  <%= form.label :image %>
  <%= form.file_field :images, multiple: true %>
</div>

画像表示ページの編集

最後に保存した画像の表示をします。
@post.image.attached?で画像が存在するか確かめています。

app/views/posts/index.html.erb
<% if @post.image.attached? %>
  <% @post.image.each do |image| %>
    <%= image_tag image.variant(resize: '500x500') %>
  <% end %>
<% end %>

これで、実装できました!

最後に

以上で画像投稿の複数化は完了です。
画像投稿機能が導入されていれば簡単に実装できるので、ぜひ試してみてください。
では。

10
6
0

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
10
6