Rails 5.2 Active Storage purging/deleting attachments Rails 5.2 Active Storage purging/deleting attachments ruby-on-rails ruby-on-rails

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_urlend

The route should be something like so...

resources :collections do  member do    delete :delete_image_attachment  endend

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_urlend

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_urlend

This removed both attachment and blob record.


Thanks for your update regarding Blob vs Attachment! After purging the attachment I redirect_back to the form I came from like this:

def remove_attachment  attachment = ActiveStorage::Attachment.find(params[:id])  attachment.purge # or use purge_later  redirect_back(fallback_location: collections_path)end

Not the best solution to reload the entire page but works ...