0

I have a user model where users can upload their profile image, using the Paperclip gem. This all works fine and stores the file in the /public/images/#{user.id}/medium or original or small directory.

However I need to create an method to be able to delete these files, could someone help me with this?

Here is the code I have so far:

app/views/users/index.html.erb:

<%= link_to "Delete", method: :file_cleanup, action: :destroy %>

app/controllers/users_controllers.rb:

def file_cleanup
    File.delete(Rails.root + 'public/#{current_user.image.url}')
    redirect_to :action => :edit
end

I have not added any routes as the page seems to load without any errors.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Jon
  • 23
  • 6

1 Answers1

1

It should be as simple as:

def delete_image
  @user.image.destroy
end

I'd use that as a hook like before_destroy :delete_image.

See: Rails Paperclip how to delete attachment?

Community
  • 1
  • 1
CDub
  • 13,146
  • 4
  • 51
  • 68
  • How simple! Thank you so much, sometimes I forget that Ruby/Rails is actually so kind to its developers. Thank you very much for your help and your prompt reply :) – Jon Oct 11 '13 at 14:10
  • @user2339235 If it did help, please close this question by clicking the checkbox next to this answer. :) – CDub Nov 04 '13 at 16:30