2015-07-13 137 views
7

我使用的是從master分支和PostgreSQL上的多個文件上傳 我的產品模型有一個名爲「images」的字符串字段,我可以附加多張圖片就好了。Carrierwave多圖像上傳

雖然我弄不清楚,我怎樣才能從產品中刪除一張圖片? 我可以刪除在該文檔中描述的所有圖片:

product.remove_images! 
product.save 

,但沒有找到一種方法如何刪除單個圖像。

+1

你有'圖像'或'圖像'作爲屬性名稱嗎? – Pavan

+0

「從主分支上傳多個文件」 - 除了carrierwave之外還有一個gem,或者你是什麼意思? – amiuhle

+0

檢查https://github.com/carrierwaveuploader/carrierwave#multiple-file-uploads 它說:注意:您必須指定使用主分支啓用此功能: – Cris

回答

0

您應該可以在指定圖像上使用remove_image(來自陣列)。所以你需要以某種方式首先識別圖像(例如:images[0].remove_image!

+0

不幸的是這不起作用:( – Cris

3

你使用嵌套形式嘗試刪除的圖像考慮?

下面是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'在你的Gemfile。

希望這可以幫助你。

+0

只有一個屬性,嵌套表單應該用在哪裏?如果你閱讀master分支上的自述文件:https://github.com/carrierwaveuploader/carrierwave#多文件上傳 我havea存儲陣列單列。如果我對圖像一個獨立的模型,我不知道。 我開始看mount_multiple_spec 您的解決方案是可行的。rb來自carrierwave,我開始認爲現在有辦法。 – Cris

0

在產品模型中加入類似的東西會有訣竅。

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還負責刪除文件。

1

我從@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 

我寫了blog post這一點,並創建一個更具體的代碼的sample project