Mongoid: before_destroy and paranoia

Are there some callbacks for soft delete in Mongoid? Because before_destory will not be launched.

Now I thought I could use before_update , but it doesn’t look as clear as I want, and it also does not start

 class Message include Mongoid::Document include Mongoid::Timestamps include Mongoid::Paranoia before_update :some_action private def some_action if self.deleted_at_changed? ... # do my stuff end end end 

So, the only solution is to call it from killing actions in the controller?

+4
source share
3 answers

Mongoid supports paranoid documents.

What you do is a combination of Paranoia mixin:

 class Person include Mongoid::Document include Mongoid::Paranoia end 

Then observe the following new features:

 person.delete # Sets the deleted_at field to the current time. person.delete! # Permanently deletes the document. person.destroy! # Permanently delete the document with callbacks. person.restore # Brings the "deleted" document back to life. 

You can find this information in the additional part of the documentation on the mogoid website here .

+2
source

What I've done:

 def delete_with_callbacks run_callbacks(:destroy) { delete_without_callbacks } end alias_method_chain :delete, :callbacks 
+2
source

As Tyler mentioned, you can use Mongoid::Paranoia . This will give you another option:

 message.remove 

To check if it has been deleted or not, you can use message.destroyed? .

Also Message.deleted will bring you all the deleted (deleted) entries from the Message class.

Check out their beautiful documentation with this one .

+1
source

All Articles