Ruby on Rails gem "CarrierWave":画像削除実装

scaffoldで下準備

scaffoldを用いて生成.モデル名はPostとした.

$ rails g scaffold Post name:string image:string

Viewの変更(index)

createアクションで画像が設定されていないとnilが返ってくるため、nilでなければ画像を表示するように設定.

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Image</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.name %></td>
        <td><% unless post.image.url.nil? %> <%= image_tag post.image.url %> <% end %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

Viewの変更(create)

画像登録フォームを作成するため[/app/views/posts/_form.html.erb]を以下のように変更.

  <div class="field">
    <%= form.label :image %>
    <p><%=form.label "画像をアップロード" %><br><%= form.file_field :image %></p>
  </div>

不格好だけどこんな感じ.

f:id:Kurorera:20190512045518p:plain:w200f:id:Kurorera:20190512045626p:plain

Destroy アクションに画像削除用コマンドを記入

以下サイトより、"remove_{カラム名}!"で削除できるとのことなのでdestroyアクションの初め2行に追加.
CarrierWaveでアップロードしているファイルを削除する - Qiita

  def destroy
    @post.remove_image!
    @post.save
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

削除完了.