正在删除多个图像的活动存储阵列中的单个图像

问题描述 投票:0回答:1

在编辑页面上,我已显示上载到活动存储数据库的产品的所有图像,并在其下方显示了该图像的专用删除按钮。如果我手动插入ID,代码将删除图像,但是我的代码发送的ID给出了图像在阵列中的位置。如何从阵列位置编号中找到链接到图像的实际ID?

如果有更简单的方法可以做到这一点,也将不胜感激。

views / admin / products / _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

def delete_image_attachment
  @image = ActiveStorage::Attachment.find(params[:id])
  @image.purge
  redirect_to contact_url
end

routes.rb

namespace :admin do
  resources :products do
    member do
      delete :delete_image_attachment
    end
  end
end
ruby-on-rails activerecord ruby-on-rails-5 rails-activestorage
1个回答
1
投票

让我们开始减少路线的迷路。

namespace :admin do
  resources :products do
    resources :images, only: :destroy
  end
end

这将创建RESTful嵌套路由DELETE /admin/products/:product_id/images/:id,而不是奇怪的RPC样式delete_image_attachment路由。如果图像ID是唯一的,您还可以使用shallow: true选项对路线进行嵌套。您的路线存在的问题是它包含ID,但位置错误。当您查看时:

shallow: true

这意味着它将删除products/1/delete_image_attachment 的附件。实际发生的不是ID为1的图像。

当您进行迭代时,仅遍历集合而不是其索引:

products/1

不要执行<% @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 %> ,然后在Ruby中使用each |index|获得该项目。它是反模式,things[index]创建一个完全可以避免的数据库查询。如果同时需要该项目及其位置,请使用@admin_product.images.count

© www.soinside.com 2019 - 2024. All rights reserved.