callbacks
Mongoid supports the following callbacks:
- after_initialize
- before_validation
- after_validation
- before_create
- around_create
- after_create
- before_update
- around_update
- after_update
- 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.
class Article include Mongoid::Document field :name, type: String field :body, type: String field :slug, type: String before_create :generate_slug protected def generate_slug self.slug = name.to_permalink end end
Callbacks are coming from ActiveModel, so you can use the new syntax as well:
class Article include Mongoid::Document field :name, type: String set_callback(:save, :before) do |document| document.generate_slug end protected def generate_slug self.slug = name.to_permalink end end