module Mongoid::Relations::Synchronization::ClassMethods

Public Instance Methods

synced(metadata) click to toggle source

Set up the syncing of many to many foreign keys.

@example Set up the syncing.

Person.synced(metadata)

@param [ Metadata ] metadata The relation metadata.

@since 2.1.0

# File lib/mongoid/relations/synchronization.rb, line 112
def synced(metadata)
  unless metadata.forced_nil_inverse?
    synced_save(metadata)
    synced_destroy(metadata)
  end
end

Private Instance Methods

synced_destroy(metadata) 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(metadata)

@param [ Metadata ] metadata The relation metadata.

@return [ Class ] The class getting set up.

@since 2.2.1

# File lib/mongoid/relations/synchronization.rb, line 156
def synced_destroy(metadata)
  set_callback(
    :destroy,
    :after
  ) do |doc|
    doc.remove_inverse_keys(metadata)
  end
  self
end
synced_save(metadata) 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(metadata)

@param [ Metadata ] metadata The relation metadata.

@return [ Class ] The class getting set up.

@since 2.1.0

# File lib/mongoid/relations/synchronization.rb, line 135
def synced_save(metadata)
  set_callback(
    :save,
    :after,
    if: ->(doc){ doc.syncable?(metadata) }
  ) do |doc|
    doc.update_inverse_keys(metadata)
  end
  self
end