我有一个表单,用户可以看到上传的图像,也可以一次删除一个图像。但是我想要的是每个图像旁边都有复选框,以便用户可以选择要删除的图像,然后按一个按钮将其删除。
现在这就是我所拥有的:
<% 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
我该如何完成我想要的?如果有人可以给我一个例子,我将不胜感激:)
答案 0 :(得分:0)
在您的视图中,您需要为每个图像定义一个复选框,可以通过单击按钮提交的表单来对其进行选择
const myObject = {};
const myArray = []
for (let i=0; i<=2000; i++) {
myObject['prop'+i] = i;
}
for (let k=0; k<=2000; k++) {
myArray[k] = k;
}
const t0 = window.performance.now();
for (const key in myObject) {
if (myObject[key] % 37 === 0) {
//console.log(myObject[key] + ' is a multiple of 37');
}
}
const t1 = window.performance.now();
console.log('Looping object with for...in: ' + (t1 - t0).toFixed(2) + 'ms');
const t2 = window.performance.now();
myArray.forEach((item) => {
if (item % 37 === 0) {
//console.log(item + ' is a multiple of 37');
}
});
const t3 = window.performance.now();
console.log('Looping array with forEach: ' + (t3 - t2).toFixed(2) + 'ms');
const t4 = window.performance.now();
const newArray = myArray.filter((item) => item % 37 === 0);
const t5 = window.performance.now();
console.log('Looping array with filter: ' + (t5 - t4).toFixed(2) + 'ms');
const t6 = window.performance.now();
const newArray2 = myArray.map((item) => item*2);
const t7 = window.performance.now();
console.log('Looping array with map: ' + (t7 - t6).toFixed(2) + 'ms');
在您的控制器中,您可以执行以下操作:
vehicles_controller.rb:
<%= 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 %>
请随时提出任何疑问
答案 1 :(得分:0)
我最终做的事情有所不同,但是非常感谢@Sandepp Garg帮助我到达那里。
因为rails不支持另一个表单中的表单,所以我无法使用Sandepp的答案。我使用更新操作来删除图像。我不知道这是否是最好的方法,但是那是我的方法。
#controller
def update
attachments = ActiveStorage::Attachment.where(id: params[:deleted_img_ids])
attachments.map(&:purge)
if @vehicle.update(vehicle_params)
redirect_to @vehicle
else
render 'edit'
end
end
<!-- view -->
<div class="box_image">
<div class="box_content">
<%= image_tag img %>
<%= check_box_tag "deleted_img_ids[]", img.id %>
</div>
</div>
如果我确实做错了什么,请告诉我。谢谢:)