Search code examples
ruby-on-railsrubyformtasticcarrierwaveactiveadmin

Rails 3 Carrierwave How to delete file which is an attribute of a model?


I followed the Railcast #253 http://railscasts.com/episodes/253-carrierwave-file-uploads and works great. But then I implemented it with ActiveAdmin and therefore Formtastic (ActiveAdmin uses Formtastic for the forms).

So I'm able to upload files and download files.

Problem is, it seems that Carrierwave expects a model instead of an attribute of the model when linking to remove links.

I have model Shipment, which has hbl_pdf attribute (a PDF document). This is my delete link...

row("HBL") { link_to 'remove', shipment.hbl_pdf, :confirm => "Are you sure?", :method => :delete }

I get error... undefined method model_name for PdfUploader:Class

I don't want to delete the shipment, only the document.


Solution

  • Why aren't you calling remove_hbl_pdf! on the shipment object instead? Read the "Removing uploaded files" section of this: https://github.com/jnicklas/carrierwave#readme

    link_to 'remove', remove_shipment_pdf_path(shipment), :confirm => "Are you sure?", :method => :delete
    

    and in your controller

    def remove_shipment_pdf
      shipment = Shipment.find_by_id(params[:shipment_id])
      shipment.remove_hbl_pdf! if shipment
      # respond with something or redirect
    end
    

    The syntax for the remove command is based on the name of your attribute. So if your model attribute name is .hbl_pdf then it is remove_hbl_pdf! and if it was .image then it would be remove_image!