LoginSignup
7
17

More than 3 years have passed since last update.

【Ruby on Rails】refileで複数画像のアップロード

Posted at

目標

refile.gif

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

前提

※ ▶◯◯ を選択すると、説明等が出てきますので、
  よくわからない場合の参考にしていただければと思います。

投稿機能が実装できていることが前提です。
※参考 ログインユーザーのみができる投稿機能

流れ

1 gemの導入
2 テーブルの作成
3 modelを編集
4 controllerを編集
5 viewを編集

※補足 【Ruby on Rails】refileでの投稿画像プレビュー機能

gemの導入

Gemfile
gem 'refile', require: 'refile/rails', github: 'refile/refile'
gem 'refile-mini_magick'
ターミナル
$ bundle install

テーブルの作成

今回はpostモデルとpost_imageモデルを作成していきます。
それぞれのカラムは下記の通りです。

db/schema.rb
 create_table "post_images", force: :cascade do |t|
    t.integer "post_id", null: false
    t.string "image_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["post_id"], name: "index_post_images_on_post_id"
  end

  create_table "posts", force: :cascade do |t|
    t.string "title", null: false
    t.string "content", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

modelを編集

app/models.post.rb
class Post < ApplicationRecord
  has_many :post_images, dependent: :destroy
  accepts_attachments_for :post_images, attachment: :image
end
app/models.post_image.rb
class PostImage < ApplicationRecord
  belongs_to :post
  attachment :image
end

controllerを編集

app/controllers/posts_controller.rb
class Admins::PostsController < ApplicationController

...

  private
  def post_params
    params.require(:post).permit(:title, :content, post_images_images: [])
  end
end

補足【post_images_images: []】
複数の画像idになるため、配列[]で渡します。

viewを編集(新規投稿)

<%= f.attachment_field :post_images_images, multiple: true %>
こちらのmultiple: trueは忘れず記述してください。
これが複数画像投稿には必要です。

app/views/posts/new.html.erb
<%= form_for(@post, url: posts_path) do |f| %>
  <table>
    <tbody>
      <tr>
        <td>画像</td>
        <td><%= f.attachment_field :post_images_images, multiple: true %></td>
      </tr>
      <tr>
        <td>タイトル</td>
        <td><%= f.text_field :title, autofocus: true %></td>
      </tr>
      <tr>
        <td>内容</td>
        <td><%= f.text_area :content %></td>
      </tr>
      <tr>
        <td></td>
        <td><%= f.submit "追加", class: "btn btn-primary" %></td>
      </tr>
    </tbody>
  </table>
<% end %>

viewを編集(投稿詳細)

複数の画像のため、each文が必要になります。
もし1枚目だけを表示したい場合は
<% @post.post_images.first(1).each do |image| %>
とすればOKです。

app/views/posts/show.html.erb
<% if @post.post_images.present? %>
  <% @post.post_images.each do |image| %>
    <%= attachment_image_tag image, :image, class: "default_image" %>
  <% end %>
<% else %>
  画像はありません。
<% end %>

投稿方法

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

参考

7
17
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
7
17