2
1

More than 3 years have passed since last update.

複数の画像投稿/表示をさせたいとき(refile使用)

Last updated at Posted at 2021-01-21

refileを使用して写真投稿/表示を行う方へ。
下記の手順で実装すれば、本来1枚しか投稿・表示できないところ、
複数の写真投稿/表示ができるようになります。

1.rifleの準備

Gemfileに下記を記入後、「bundle install」ください。

Gemfile
gem "refile", require: "refile/rails", github: 'manfe/refile'
gem "refile-mini_magick"

2.テーブルの作成

複数枚の写真を投稿・表示させる場合、
「写真を表示させるモデル」と「写真を保存しておくテーブル」が必要になります。

db/schema.rb
create_table "shops", force: :cascade do |t|
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "shop_images", force: :cascade do |t|
  t.string "shop_image_id"
  t.integer "shop_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

3.モデルの設定

先ほど作成したテーブルのモデルにて、それぞれの関係を1:多の関係で紐付ける必要があります。
(ここでは例として、「shopモデル」に紐づく「shop_imageモデル」で解説しています。
「shop」はあくまで例ですので、ご自身の作成されているモデル名に合わせて修正ください)

shop.rb
 has_many :shop_images, dependent: :destroy
 #1:多の紐付け
 accepts_attachments_for :shop_images, attachment: :shop_image
 #shop_image(_id)をshopのviewにて表示させるための設定
shop_image.rb
 belongs_to :shop
 #1:多の紐付け
 attachment :shop_image
 #shop_image(_id)をshopのviewにて表示させるための設定

4.コントローラーの設定

shopコントローラーのnewアクション(投稿)、showアクション(一覧表示)、
ストロングパラメータをそれぞれ記述していきましょう。(※shop_imageコントローラーは作成しません)

shops_cotroller.rb
def new
  @shop = Shop.new
  #空データを作成
  @shop.shop_images.new
  #写真の空データを作成
end

def show
  Shop.find(params[:id)
end

private
def shop_params
  params.require(:shop).permit(shop_images_shop_images: [])
  #shop_images_shop_images → shop_imagesテーブルの複数のshop_imageを指定
  #: [] → 指定した複数のshop_imageを配列に入れます(配列に入れて管理するため)
end

5.ビューの記述

投稿ページ(new.html)と投稿ページ(show.html)を記述していきましょう。

app/views/shops/new.html.erb
<%= form_with model: @shop, local:true do |f| %>
<table>
  <tbody>
    <td>
     <%= f.attachment_field :shop_images_shop_images, multiple: true %>
    </td>
  </tbody>
</table>
<% end %>

↑「multiple:true」にすることで複数投稿が可能になります。

app/views/shops/show.html.erb
<table>
  <td>
  <% if @shop.shop_images.present? %>
    <% @shop.shop_images.each do |shop_image| %>
      <%= attachment_image_tag shop_image, :shop_image, :fill, 200, 200 %>
    <% end %>
  <% else %>
    <%= image_tag "no_image.jpg", size: "200x200" %>
  <% end %>
  </td>
</table>

↑「no_image.jpg」は別途用意していただく必要があります。
app/assets/imagesに用意頂いたデータを入れてください。
no_image_jpg (urlを開いていただいた後、右クリックでダンロードください)

6.ブラウザ上にて複数の画像を選択する方法

複数の画像をアップロードする場合は、「ファイル選択」をクリック後、
Shift + クリック, またはCtrl + クリックで画像を選択ください。

参考にした記事

2
1
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
2
1