[英]Carrierwave multiple image upload
我正在使用來自主分支的多個文件上傳和PostgreSQL我的產品模型有一個名為“images”的字符串字段,我可以很好地附加多個圖像。
雖然我無法弄清楚,如何從產品中刪除一張圖片? 我可以刪除文檔中描述的所有圖像:
product.remove_images!
product.save
但沒有找到如何刪除單個圖像的方法。
您是否考慮過使用嵌套表單來嘗試刪除圖像?
這是來自carrierwave的github網站的一段代碼......
<%= form_for @product, html: { multipart: true } do |f| %>
.
.
.
<label>
<%= f.check_box :remove_images %>
Remove images
</label>
<% end %>
......我相信你已經看過了。 當然,雖然調用remove_images!
在你的情況下不起作用,因為這意味着對所有圖像采取統一的行動。
嘗試以上的上述修改,看看它是否有助於您排序此問題並單獨定位每個圖像...
<%= nested_form_for @product, :html=>{ :multipart => true } do |f| %>
.
.
.
<%= f.fields_for :images do |product_form| %>
<%= product_form.link_to_remove "Remove this image" %>
<% end %>
<% end %>
要完成這項工作,請確保在gem 'nested_form', '~> 0.3.2'
包含gem 'nested_form', '~> 0.3.2'
。
希望這會幫助你。
我從@Cris學習並在使用S3時使用以下代碼片段。
def remove_image_at_index(index)
remain_images = @product.images # copy the array
deleted_image = remain_images.delete_at(index) # delete the target image
deleted_image.try(:remove!) # delete image from S3
@product.images = remain_images # re-assign back
end
您應該能夠在指定的圖像上使用remove_image
(來自數組)。 所以你需要先以某種方式識別圖像(例如images[0].remove_image!
)
在產品模型中添加這樣的東西就可以了。
def delete_image(idx)
remaining_images = []
self.images.each_with_index { |img,ii| remaining_images<<File.open(img.path) unless idx == ii}
self.images=remaining_images
end
保存記錄后,Carrierwave還負責刪除文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.