Rails 5.2 Active Storage purging/deleting attachments

You are looping through the collection of images and calling the purge method on each one. Instead you should be linking to a destroy method on your controller, something like the below taking into account your controller actions and guessing at your route names.

The error is because image object returns its full path and the link thinks that what you want to point to. Instead you just want its signed_id and want the link to call the route that has your delete_image_attachment path.

 <%= link_to 'Remove', delete_image_attachment_collections_url(image.signed_id),
                method: :delete,
                data: { confirm: 'Are you sure?' } %>

The destroy method would look something like this...

def delete_image_attachment
  @image = ActiveStorage::Blob.find_signed(params[:id])
  @image.purge
  redirect_to collections_url
end

The route should be something like so...

resources :collections do
  member do
    delete :delete_image_attachment
  end
end

Check out the rails routing guide for more fun routing facts.


The following didn't work for me.

def delete_image_attachment
  @image = ActiveStorage::Blob.find_signed(params[:id])
  @image.purge
  redirect_to collections_url
end

So what i did is found the attachment and purged it. You can do purge_later which is recommended.

def delete_image_attachment
  @image = ActiveStorage::Blob.find_signed(params[:id])
  @image.attachments.first.purge
  redirect_to collections_url
end

This removed both attachment and blob record.