Rails 4 Devise reactivate “soft deleted” accounts

2019-07-12 13:51发布

问题:

Followed this tutorial on how to do a soft-delete, which works. But if a user decides they want to go back and reactivate the account, what would be the best way to do so? Or is there a wiki for this as well? I couldn't find it.

回答1:

Looking at the tutorial link you posted, they used time (deleted_at) to determine if a user is deleted (soft-delete).

You can now have a separate route and method for re-activating a user if the login credentials are correct i call mine reactivate_user

# app/models/user.rb  

  # instead of deleting, indicate the user requested a delete & timestamp it  
  def soft_delete  
    update_attribute(:deleted_at, Time.current)  
  end  

  def reactivate_user  
    update_attribute(:deleted_at, nil)  
  end 
  # ensure user account is active  
  def active_for_authentication?  
    super && !deleted_at  
  end  

  # provide a custom message for a deleted account   
  def inactive_message   
    !deleted_at ? super : :deleted_account  
  end