2015-09-29 120 views
1

我的模型中有多個Carrierwave附件字段,我希望能夠在我的show view中刪除它。由於有多個字段我將參數傳遞給我的控制器方法,所以它知道要刪除的文件:基於參數的Carrierwave刪除方法

def remove_attachment 
    post = Post.find(params[:id]) 
    post["remove_#{params[:attachment]}!"] 
    post.save 
    redirect_to post 
end 

但是,下面的行不工作post["remove_#{params[:attachment]}!"]?不知道我在哪裏錯了嗎?

我測試過它不工作的情況如下:

def remove_attachment 
    post = Post.find(params[:id]) 
    post.remove_compliance_guide! # one of the attachment fields 
    post.save 
    redirect_to post 
end 

我意識到,我可以做下面的,但我想我的第一個解決方案是清潔的。

def remove_attachment 
    post = Bid.find(params[:id]) 

    if params[:attachment] == 'compliance_guide' 
    post.remove_compliance_guide! 
    elsif params[:attachment] == 'compliance_other' 
    post.remove_compliance_other! 
    elsif params[:attachment] == 'compliance_agreement' 
    post.remove_compliance_agreement! 
    end 
    post.save 
    redirect_to post 
end 

以防萬一,我犯了一個錯誤在其他地方:

路線:post 'posts/:id/remove_attachment', to: 'posts#remove_attachment'

查看鏈接:link_to 'Remove', { controller: 'post', action: "remove_attachment", attachment: 'compliance_guide', id: @post.id }, method: 'post', class: "file-remove right"

回答

2

可以使用send通過傳遞它的名字來調用一個方法作爲字符串:

def remove_attachment 
    post = Post.find(params[:id]) 
    post.send("remove_#{params[:attachment]}!") 
    post.save 
    redirect_to post 
end 

請注意,如果附件不存在,將會產生NoMethodError。你可以使用類似的東西來解決這個問題:

if post.respond_to?("remove_#{params[:attachment]}!") 
    post.send("remove_#{params[:attachment]}!") 
    post.save 
end 
+0

好人,謝謝你的回答完美。 –

+0

很高興能幫到你!另請查看我對可能的'NoMethodError'所做的評論,以防它適用於您的應用。 – Drenmi

+0

謝謝,它確實適用於我的應用程序。非常感謝! –