Callbacks
Callbacks are pretty interesting in Mongoid. Just as validations, Mongoid leverages ActiveModel::Callbacks
. Callbacks are methods that are called along with persistence. This helps us manipulate the data. We can implement various callbacks such as before_save
, after_create
, and before_destroy
. The entire list of callbacks is available at http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html.
Note
Did you know ActiveModel::Callbacks
include after_initialize
, after_find
, after_touch
, after_commit
, and after_rollback
? Of course, after_commit
and after_rollback
are specific to transactional databases unlike MongoDB.
Mongoid also supports before_upsert
, after_upsert
, and around_upsert
! As we have seen earlier, an upsert means "update if the document exists and create if it doesn't exist". However, there's more to callbacks in Mongoid.
Mongoid also supports the after_add
, after_remove
, before_add
, and before_remove
callback for some specific relations. Let's dive deeper into this...