Rails foundationSort Order

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.

Purge Method

Removing attachment is quite simple we can call the purge method.

# load the post with attachmentpost = Post.first# call the purgepost.cover_picture.purge# we can also use the async versionpost.cover_picture.purge_later

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    cover_picture.purge_later  end    # ...end

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| %>  <div class='form-group'>    <%= 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 %>  </div>  # ...<% 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  # ...  private  # ...    # add :remove_cover_picture  def post_params    params.require(:post).permit(      :state_event,       :remove_cover_picture,       :cover_picture,       :title, :body, :tag_ids => []    )  endend

That should be it! We should now be able to remove the attachment if we have one uploaded!