I have the following models:
class User
include Mongoid::Document
embeds_one :courier, class_name: "Users::Courier"
validates_associated :courier
accepts_nested_attributes_for :courier
end
module Users
class Courier
include Mongoid::Document
embedded_in :user
after_create :foo
def foo
puts "courier created"
end
end
but this callback is only run if i call save
directly on the courier object, not when i save the parent object.
Thus having a nested form and a controller that creates the user including the courier does not run the create callback of the courier.
The mongoid documentation says that this is by design:
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.
But how can i write code that gets executed whenever a courier is created? In my case i cannot run the code in the user's after_create callback, because there are users that do not have the embedded document courier. But when a courier gets added i want to run a callback.
Whats the best option to do so?
found the answer:
embeds_one :courier, class_name: "Users::Courier", cascade_callbacks: true