Callbacks

Document Callbacks

Mongoid supports the following callbacks:

  • after_initialize
  • after_build
  • before_validation
  • after_validation
  • before_create
  • around_create
  • after_create
  • after_find Since 3.1.0
  • before_update
  • around_update
  • after_update
  • before_upsert
  • around_upsert
  • after_upsert
  • before_save
  • around_save
  • after_save
  • before_destroy
  • around_destroy
  • after_destroy

Callbacks are available on any document, whether it is embedded within another document or not. Note that to be efficient, Mongoid only fires the callback of the document that the persistence action was executed on. This is that Mongoid aims to support large hierarchies and to handle optimized atomic updates callbacks can't be firing all over the document hierarchy.

Using callbacks for domain logic is a bad design practice, and can lead to unexpected errors that are hard to debug when callbacks in the chain halt execution. It is our recommendation to only use them for cross-cutting concerns, like queueing up background jobs.

class Article
  include Mongoid::Document
  field :name, type: String
  field :body, type: String
  field :slug, type: String

  before_create :send_message

  after_save do |document|
    # Handle callback here.
  end

  protected
  def send_message
    # Message sending code here.
  end
end

Callbacks are coming from Active Support, so you can use the new syntax as well:

class Article
  include Mongoid::Document
  field :name, type: String

  set_callback(:create, :before) do |document|
    # Message sending code here.
  end
end

Relation Callbacks

Since 3.1.0

Mongoid has a set of callbacks that are specific to collection based relations - these are:

  • after_add
  • after_remove
  • before_add
  • before_remove

Each time a document is added or removed from any of the following relations, the respective callbacks are fired: embeds_many, has_many, and has_and_belongs_to_many.

Relation Callbacks are specified as an option on the relation. The element added/removed is the parameter to the method you call via the callback. Example:

class Person
  include Mongoid::Document

  has_many :posts, after_add: :send_email_to_subscribers
end

def send_email_to_subscribers(post)
  Notifications.new_post(post).deliver
end