3
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.

refileを使って複数画像アップロード

Last updated at Posted at 2021-01-24

某プログラミングスクールにてポートフォリオ作成中。
忘れないようこちらに記載しておきます。
画面収録 2021-01-24 9.12.06.mov.gif
field(会場)はdeviseで作成しています。
https://qiita.com/japwork/items/dcca7ead2d3c334b124c
この記事だけではうまくできなかったため、メンターに質問してやっと解決できました。
4日ほどここでつまづいてました。。。

schema.rb
 create_table "pictures", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "image_id"
    t.integer "post_id"
  end

  create_table "posts", force: :cascade do |t|
    t.integer "field_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

名前がややこしいですが。。
field(会場)がたくさんのpost(投稿)をできて、
postにはたくさんのpicture(写真)が入ってます。

routes.rb
Rails.application.routes.draw do
  devise_for :fields, controllers: {
    sessions:      'fields/sessions',
    passwords:     'fields/passwords',
    registrations: 'fields/registrations'
  }
  resources :fields
  resources :posts, only: [:new, :create, :show] do
    resources :pictures
  end
end
post.rb
class Post < ApplicationRecord
  has_many :pictures
  belongs_to :filed, optional: true
  accepts_attachments_for :pictures, attachment: :image
end
picture.rb
class Picture < ApplicationRecord
  belongs_to :post
  attachment :image
end
posts_conttoller.rb
class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    @post.field_id = current_field.id
    @post.save
    redirect_to post_path(current_field)
    @posts = Post.all
  end

  def show
    @posts = Post.where(field_id: current_field.id)
  end

  private
  def post_params
    params.require(:post).permit(pictures_images: [])
  end
end

posts/new.html.erb
<h2>Posts#new</h2>

<%= form_with model: @post, local: true do |f| %>
  <%= f.hidden_field :field_id, :value => current_field.id %>
  <%= f.attachment_field  :pictures_images, multiple: true %>
  <%= f.submit "投稿する" %>
<% end %>
posts/show.html.erb
<%= link_to "写真追加", new_post_path %><br>

<% if current_field.posts.present? %>
  <% @posts.each do |post| %>
    <% post.pictures.each do |picture| %>
      <%= attachment_image_tag picture, :image, :fill, 100, 100, class: "mb-1" %>
    <% end %>
  <% end %>
<% else %>
  投稿写真はありません。
<% end %>

コントローラーの途中で

 puts "---"
 pp @posts
 puts "---"

と入力するとターミナルで中身の確認ができます。

3
0
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
3
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?