[英]Deleting single image in array of multiple images active storage
On my edit page, I have displayed all images of the product uploaded to the active storage database and below it a dedicated delete button for that single image.在我的编辑页面上,我显示了上传到活动存储数据库的产品的所有图像,并在其下方为该单个图像提供了一个专用的删除按钮。 The code deletes the image if I manually insert the id, but the id sent by my code gives the location of the image in the array.
如果我手动插入 id,代码会删除图像,但我的代码发送的 id 给出了图像在数组中的位置。 How do I find the actual id linked to the image from the array location number?
如何从数组位置编号中找到链接到图像的实际 id?
If there is an easier method to do this that would also be appreciated.如果有更简单的方法来做到这一点,那也将不胜感激。
views/admin/products/_formedit.html.erb意见/管理/产品/_formedit.html.erb
<% (0...@admin_product.images.count).each do |image| %>
<%= image_tag(@admin_product.images[image]) %>
<%= link_to 'Remove', delete_image_attachment_admin_product_url(image), method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
controllers/admin/products_controller.rb控制器/管理员/products_controller.rb
def delete_image_attachment
@image = ActiveStorage::Attachment.find(params[:id])
@image.purge
redirect_to contact_url
end
routes.rb路线.rb
namespace :admin do
resources :products do
member do
delete :delete_image_attachment
end
end
end
Lets start by making the routes less wonky.让我们首先让路线不那么不稳定。
namespace :admin do
resources :products do
resources :images, only: :destroy
end
end
This creates a RESTful nested route DELETE /admin/products/:product_id/images/:id
instead of a strange RPC style delete_image_attachment
route.这将创建一个 RESTful 嵌套路由
DELETE /admin/products/:product_id/images/:id
而不是奇怪的 RPC 样式delete_image_attachment
路由。 You can also use the shallow: true
option to de-nest the route if the image id is unique.如果图像 id 是唯一的,您还可以使用
shallow: true
选项来取消嵌套路由。 The problem with your route is that it includes an ID but its in the wrong place.您的路线的问题在于它包含一个 ID,但它在错误的位置。 When you look at:
当你看:
products/1/delete_image_attachment
It would imply that it deletes the attachment for products/1
.这意味着它会删除
products/1
的附件。 And not the image with id 1 with is what is actually happening.而不是 id 为 1 的图像是实际发生的事情。
When your iterating just iterate through the collection and not its indices:当您的迭代只是迭代集合而不是它的索引时:
<% @admin_product.images.each do |image| %>
<%= image_tag(image) %>
<%= link_to 'Remove',
admin_product_image_path(@admin_product, image),
method: :delete,
data: { confirm: 'Are you sure?' }
%>
<% end %>
Don't do each |index|
不要
each |index|
and then get the item with things[index]
in Ruby.然后在 Ruby 中获取带有
things[index]
的项目。 Its an anti-pattern and @admin_product.images.count
creates a completely avoidable database query.它是一种反模式,
@admin_product.images.count
创建了一个完全可以避免的数据库查询。 If you need both the item and its position use each_with_index
.如果您需要该项目及其 position ,请使用
each_with_index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.