2014-09-10 65 views
2

我發現這個solution使用複選框作爲標誌刪除圖像。但是,我想使用link_to。基本上,在圖片附件旁邊,我想要一個「刪除頭像」鏈接。如果可能,我希望鏈接只刪除圖像,而不更新其他屬性。如何使用link_to刪除Paperclip附件?

User類

class User < ActiveRecord::Base 
    has_attached_file :avatar 
    attr_accessible :avatar 

在形式

link_to "Delete Avatar", {:action => :update}, :method => :put 

顯然,這並不實際刪除圖像,只是還沒有。什麼是最好的方法來做到這一點?讓鏈接設置一個隱藏的標誌,然後更新?或者這只是一個壞主意(如果是的話)?

回答

7

創建一個補丁路線,以刪除與USER_ID附件和匹配作用在控制器

link_to 'Delete Avatar', {action: :action_name, id: user.id}, method: :put 

def action_name 
    # use either/or depending on your usecase 
    @user.avatar.destroy #Will remove the attachment and save the model 
    @user.avatar.clear #Will queue the attachment to be deleted 
end