Search code examples
ruby-on-railsrails-activerecorddelete-filelink-to

Active Record/Ruby on Rails -> Delete image by click on link: Set attachment columns to NULL via


I am not sure how to do this. I have a table called "animals". Then i can add an image to display the animal.

I use this statement in the form-view for changing the image:

f.file_field :attachment, :accept => 'image/jpeg'

When i submit the form i got a nice looking image in my show-view.

Like i said, i can easily change the image, but i do not know exactly how to delete it. In a perfect world i would prefer, i press a link and the image gets just deleted, but the rest of the animals attributes stay alife, so the following columns are set to NULL and the file gets deleted from the server:

"attachment_file_name" "attachment_content_type" "attachment_file_size" "attachment_update_at" (should probably be set to the current date, or set to NULL)

Any help apreciated.


Solution

  • If you are using paperclip gem all you need to do is set attachment to nil and save. Like this:

    @animal.attachment = nil
    @animal.save
    

    More info here

    In your case, if you want to add a link to remove, you will create a route and an action just to do this.

    I suggest adding a checkbox nearby the file field and verify it at update/create.