Search code examples
ruby-on-railsmodeldevisecallback

Rails devise before_destroy user


I wan't to notify the admin when a user deletes his account. My idea is to use the before_destroy validation to send an email from within the model.

This is probably better done in the controller but I don't want to subclass the devise controller because I think I could break something.

The problem is that the model can't access the current_user, which was my first thought about how to "get" the corresponding user account. But the model has to somehow know which user account is meant to be destroyed, right?, so there has to be some kind of variable being passed.

I've looked into the devise controller at github and it seems like everything is done using "resources".

https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb

I can't figure out the last part, how could I access the id / or user object?


Solution

  • Simple add a hook in your model and send the mail..

    class User < ActiveRecord::Base
    
      before_destroy :notify_admin
    
    
      private
    
      def notify_admin
        YourMailer.user_destroyed(self).deliver
      end
    
    end
    

    The "self" will be your current_user object..