All threads / I need help to get delete of attachments to work from view with ActiveStorage

Ask A Question


You’re not receiving notifications from this thread.

I need help to get delete of attachments to work from view with ActiveStorage

[email protected] asked in Rails

Hello, I am on Rails 5.2.3.
I just followed the rails guide on ActiveStorage, and have the attachments working. from a display, download link POV.
What I do not seem to get functioning is the delete of a single attachment via a link or button in my view. And then when the delete is done, i would it to refresh my view while staying on the same page.

Somehow with the code below, and likely the settings in my routes file, instead of going to delete_image it goes to destroy of the same controller, and of course can't do anything with what the parameter hands it.

I am not attached to the method chosen, as long as I can succeed in deleting the field from the view.

Any help is appreciated.

here is what I have in my view:
<% if @tr.image.attached? %>

<% @tr.image.each do |document| %>

<%= link_to document.blob.filename, url_for(document), target: :_blank %>

<%= image_tag url_for(document), size:100 %>

<%= link_to 'Download', document, download: document %>
<%= link_to 'Delete', delete_image_tr_path(document), method: :delete, data: { confirm: 'Are you sure?' }%>

<% end %>

<% end %>

in the controller I added :

def delete_image
@nowpath = params[:nowpath]
@image = ActiveStorage::Attachment.find(params[:id])
logger.debug "++++ in delete image --------------------" + @image.inspect + "---------------------"
redirect_to tr_path

and in my routes I have :
get '/tr/delete_image/:id', to: 'tr#delete_image', as: :delete_image_tr

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 48,387+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.