Rails: Active Storage Removing Attachment
Now that we can add a cover picture attachment to our application the next thing we need to do is the ability to remove it. We'll need to do a few things to get this setup.
Removing attachment is quite simple we can call the purge method.
# load the post with attachment
post = Post.first
# call the purge
# we can also use the async version
Setting up Attribute Accessor for Purging
We want to use the web form to toggle the purging of the attachment first we need to setup the attr_accessor in our model.
class Post < ApplicationRecord
# add :remove_cover_picture to attr_accessor
attr_accessor :state_event, :remove_cover_picture
# add purge_cover_picture callback
after_save :purge_cover_picture, if: :remove_cover_picture
private def purge_cover_picture
This should now take care of triggering the purge cover picture when the remove_cover_picture is detected.
Submitting the Form Attribute
We need to add the remove_cover_picture attribute to the form so the user can select it. We'll do this in app/views/admin/posts/_form.html.erb
<%= form_for [:admin, @post] do |f| %>
<%= f.label :cover_picture %>
<%= f.file_field :cover_picture %>
# add this section
<% if @post.cover_picture.attached? %>
<%= image_tag @post.cover_picture.variant(resize: '470x470') %>
<%= f.label :remove_cover_picture %>
<%= f.check_box :remove_cover_picture %>
<% end %>
<% end %>
Updating Strong Parameters
We need to make sure that we can submit the remove_cover_picture attribute in our controller app/controllers/admin/posts_controller.rb
class Admin::PostsController < Admin::BaseController
# add :remove_cover_picture
:title, :body, :tag_ids => 
That should be it! We should now be able to remove the attachment if we have one uploaded!