3

I've found this solution that uses a checkbox as a flag to delete the image. However, I want to use a link_to. Basically, next to the image attachment, I want to have a "Delete Avatar" link. If possible, I want the link to only delete the image, and not update the other attributes.

User class

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

In the form

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

Obviously this doesn't actually delete the image just yet. What would be the best way to do this? Have the link set a hidden flag and then update? Or is this just a bad idea (if so why)?

Community
  • 1
  • 1
thisisdee
  • 878
  • 3
  • 16
  • 41

1 Answers1

8

Create a patch route to remove attachment with user_id and matching action in the controller

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
JamesDullaghan
  • 1,230
  • 11
  • 12