LoginSignup
1
4

More than 3 years have passed since last update.

refileを使用した複数画像投稿機能を作ろう

Posted at

環境

Rails 5.2.4

前提

refileを導入していること

model製作

まず、実装するためのmodelを作りましょう。

$ rails g model post title:string comment:text
$ rails g model post_image product_id:string image_id:integer image_id:string

まず、複数投稿された画像を一纏めにする親のproductモデルと
複数投稿された画像を保存する子のproduct_imageモデルを作ります。
userと結び付けたい場合は、postモデルを作る際にuser_id:integerを追加してください。

次にモデル同士のアソシエーションを作ります。

models/post.rb
has_many :post_images, dependent: :destroy
accepts_attachments_for :post_images, attachment: :image
models/post_image.rb
belongs_to :post

controller編集

controllers/posts_controller
class PostsController < ApplicationController

...

 private

  def hobby_image_params
    params.require(:post).permit(:title, :comment, post_images_images: [])
  end

end

複数画像を投稿するために、パラメータを配列で渡してあげる必要があるので、配列[]で渡します。
post_imagesのimagesでpost_images_imagesとなります。

投稿のview

views/posts/new.html.erb
<%= form_with model: @post, local:true do |f| %>
 <%= f.attachment_field :post_images_images, multiple: true %>
 <%= f.text.area :title %>
 <%= f.text_area :comment %>
 <%= f.submit '投稿' %>
<% end %>

複数投稿をするので、multiple: trueを2行目に追加します。

投稿を表示させるview

views/posts/show.html.erb
<div>
 <% posts.post_images.each do |image| %>
  <%= attachment_image_tag image, :image, size: "500x500" %>
 <% end %>
</div>

以上で実装は完了です。
投稿してみて、エラーがないかを確認してみてください。

終わりに

ここまで見て頂きありがとうございました。
間違いなどありましたら、ご指摘お願い致します。

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