2011-06-01 104 views
0

我想刪除爲模型上傳的每個單一圖像(工作有很多圖像),但現在我的代碼工作如下:我有三個圖像上傳到工作中,我想刪除一個但當我檢查圖像的複選框並提交更新操作時,它將刪除所有三個圖像。使用回形針刪除圖像

這裏是我的工作模式的代碼:

before_save :destroy_image? 

    belongs_to :category 
    has_many :images, :as => :assetable, :class_name => "Work::Image", :dependent => :destroy 

    accepts_nested_attributes_for :images, :reject_if => proc { |attributes| attributes['attachment'].blank? } 

    def image_delete 
    @image_delete ||= "0" 
    end 

def image_delete=(value) 
    @image_delete = value 
end 

private 
    def destroy_image? 
    self.images.clear if @image_delete == "1" 
    end 


end 


class Work::Image < Asset 
    has_attached_file :attachment, :styles => {:small => "200x150>", :large => "400x300>"}, 
:url => "/uploads/works/:id/:style/:basename.:extension", 
:path => ":rails_root/public/uploads/works/:id/:style/:basename.:extension" 

end 

我認爲問題是,刪除所有圖像

self.images.clear if @image_delete == "1" 

,但我不知道如何解決它。我希望在你的幫助下。

回答

1

您應該使用accepts_nested_attributes_for:allow_destroy選項。

而且在你的表格是這樣的:

<% @work.images.each do |image| %> 
    <%= f.fields_for :images, image do |image_fields| %> 
    <%= image_tag image.url(:small) %> 
    <%= image_fields.check_box :_destroy %> 
    <% end %> 
<% end %> 
+0

是的,我已經使用':allow_destroy'工作模式,並在表單視圖我得到這個 '<% - @ work.images.each做|圖片| %> <%= IMAGE_TAG image.url(:小)%> <%= f.check_box(:image_delete)%> <% end %>' – davelab 2011-06-01 12:55:35

+0

您不需要這些'image_delete'充塞在所有。 ':allow_destroy'會爲你破壞記錄。我已經更新了適合你的答案中的觀點。 – 2011-06-01 13:09:52

+0

你是對的!我改變了我的模型 'accepted_nested_attributes_for:images,:allow_destroy => true,:reject_if => proc {| attributes |屬性[ '附着']。空白? }' 和我的看法 '<% - @ work.images.each do | image | %> <%= fields_for:images,image do | image_fields | %> <%= IMAGE_TAG image.url(:小)%> <%= image_fields.check_box:attachment_delete%> <% end %> <% end %>' 但我得到這個錯誤:'未定義的方法「attachment_delete'' – davelab 2011-06-01 13:22:00