I have a form where the user can see the images uploaded and also can remove one at a time. But what I want is to have checkboxes next to each image so the user can select the images he wants to remove and then press a button to remove them.
Right now this is what I have:
<% if @vehicle.images.attached? %>
<% @vehicle.images.each do |img| %>
<div class="box_image">
<div class="box_content">
<%= image_tag img %>
<div class="overlay">
<%= link_to delete_upload_vehicle_url(@vehicle, img.id), method: :delete, data: { confirm_swal: 'Tem a certeza que quer eliminar esta imagem?' }, class:"delete_image" do %>
<i class="fa fa-times"></i>
<% end %>
</div>
</div>
</div>
<% end %>
<% end %>
def delete_upload
attachment = ActiveStorage::Attachment.find(params[:upload_id])
attachment.purge
redirect_back(fallback_location: vehicles_path)
end
resources :vehicles do
member do
delete "delete_upload/:upload_id", action: :delete_upload, as: :delete_upload
end
end
How can I accomplish what I want? If someone could give me an example I would appreciate :)
In your view you need to define a check box for each image which can be selected with a form which will be submitted on click of a button
<%= form_tag destroy_multiple_images_path, method: :delete do %>
<% if @vehicle.images.attached? %>
<% @vehicle.images.each do |img| %>
<div class="box_image">
<div class="box_content">
<%= image_tag img %>
<%= check_box_tag "deleted_img_ids[]", img.id %>
</div>
</div>
<% end %>
<% end %>
<%= submit_tag "Delete selected" %>
<% end %>
in your controller you can do following :
vehicles_controller.rb:
def destroy_multiple
attachments = ActiveStorage::Attachment.where(id: params[:deleted_img_ids])
attachments.map(&:purge)
end
Feel free to ask for any doubt