Rails 5.2 Active Storage purging/deleting attachments

后端 未结 4 2097
醉话见心
醉话见心 2020-12-06 05:19

So I\'m using Active Storage to upload multiple images attached to a Collection model. Everything works well except whenever I\'m trying to purge/delete a single attachment

4条回答
  •  佛祖请我去吃肉
    2020-12-06 05:49

    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.

提交回复
热议问题