我的模型中有多個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"
好人,謝謝你的回答完美。 –
很高興能幫到你!另請查看我對可能的'NoMethodError'所做的評論,以防它適用於您的應用。 – Drenmi
謝謝,它確實適用於我的應用程序。非常感謝! –