module Mongoid::Association::Referenced::Syncable::ClassMethods

Public Instance Methods

_synced(association) click to toggle source

Set up the syncing of many to many foreign keys.

@example Set up the syncing.

Person._synced(association)

@param [ Association ] association The association metadata.

@since 2.1.0

# File lib/mongoid/association/referenced/syncable.rb, line 115
def _synced(association)
  unless association.forced_nil_inverse?
    synced_save(association)
    synced_destroy(association)
  end
end

Private Instance Methods

synced_destroy(association) click to toggle source

Set up the sync of inverse keys that needs to happen on a destroy.

@example Set up the destroy syncing.

Person.synced_destroy(association)

@param [ Association ] association The association metadata.

@return [ Class ] The class getting set up.

@since 2.2.1

# File lib/mongoid/association/referenced/syncable.rb, line 159
def synced_destroy(association)
  set_callback(
      :destroy,
      :after
  ) do |doc|
    doc.remove_inverse_keys(association)
  end
  self
end
synced_save(association) click to toggle source

Set up the sync of inverse keys that needs to happen on a save.

If the foreign key field has changed and the document is not synced, $addToSet the new ids, $pull the ones no longer in the array from the inverse side.

@example Set up the save syncing.

Person.synced_save(association)

@param [ Association ] association The association metadata.

@return [ Class ] The class getting set up.

@since 2.1.0

# File lib/mongoid/association/referenced/syncable.rb, line 138
def synced_save(association)
  set_callback(
      :save,
      :after,
      if: ->(doc) { doc._syncable?(association) }
  ) do |doc|
    doc.update_inverse_keys(association)
  end
  self
end