Is there a way to run a callback only if an embedded document field was changed?
Currently, the following runs the callback on a normal field only if it was changed:
class user
field :email, type: String
embeds_many :connections, cascade_callbacks: true
before_save :run_callback, :if => :email_changed?
before_save :run_connection_callback, :if => :connections_changed? # DOES NOT WORK
end
Mongoid won’t define the method
connections_changed?for you, but you can define it yourself by using a virtual field inUserto keep track of when an embedded connection gets changed. That is:One shortcoming of this method is that
user.connections_changedonly gets set when the document is saved. The callbacks are cascaded in such a way that theConnectionbefore_savecallback gets called first and then theUserbefore savecallback, which allows the above code to work for this use case. But if you need to know whether any connections have changed before callingsave, you’ll need to find another method.