3
1

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 5 years have passed since last update.

画像アップロードに確認画面を挟む方法

Last updated at Posted at 2020-04-28

*既に画像投稿機能は実装できているという前提で記事を書いていきます。
画像を確認画面を挟んでアップロードする方法を記述していきます。
以前、画像投稿機能と、投稿確認画面の実装を行った際に、以下のような状況に陥りました。

・投稿確認画面では画像が表示されるのに、投稿詳細画面では画像がアップロードされていない!
・デバッグでconfirmアクション(投稿確認)の挙動を確認すると、imageだけnilと表示されている!
・SQL操作にてデータベースを確認してみても、投稿一覧に画像のデータだけ保存されてない!

これが解決した際のコード記述を以下に載せておきます。

_form.html.erb
  <div class="image">
    <%= form.label :image %>
    <%= image_tag(@picture.image.url)if@picture.image&&@picture.image.url %>
    <%= form.file_field :image %>
    <%= form.hidden_field :image_cache %>
    <p><%= form.check_box :remove_image %>画像を削除する</p>
  </div>
  <%= form.submit %>
confirm.html.erb
<%= form_with(model: @picture, url: pictures_path, local: true) do |form| %>
  <%= form.hidden_field :title %>
  <%= form.hidden_field :content %>
  <%= form.hidden_field :image_cache %>
  <p>タイトル: <%= @picture.title %></p>
  <p>本文: <%= @picture.content %></p>
  <p>
    <strong>Image:</strong>
    <%= image_tag @picture.image.url if @picture.image? %>
  </p>
  <%= form.submit "登録する" %>
  <%= form.submit '戻る', name: 'back' %>
<% end %>
pictures_controller.rb
def new
  if params[:back]
    @picture = Picture.new(picture_params)
  else
    @picture = Picture.new
  end
  
def confirm
  def new
  if params[:back]
    @picture = Picture.new(picture_params)
  else
    @picture = Picture.new
  end
end

def confirm
  @picture = Picture.new(picture_params)
end

private

def set_feed
  @picture = Picture.find(params[:id])
end

def Picture_params
  params.require(:picture).permit(:image, :image_cache)
end
routes.rb
Rails.application.routes.draw do
  resources :pictures do
    collection do
      post :confirm
    end
  end
end

ポイント
・confirm,_form.html.erbにhiddenの記述をすること。
*hidden=隠しデータをサーバーに送信する際に使用する。画面上には表示されないが、value属性で指定した値がサーバーへ送信される。
・image__cache=画像のデータそのものを取り扱うパラメータで、確認画面の実装を挟む際等に使用する。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?