Module: Mongoid::Relations::Synchronization

Extended by:
ActiveSupport::Concern
Included in:
Mongoid::Relations
Defined in:
lib/mongoid/relations/synchronization.rb

Overview

This module handles the behaviour for synchronizing foreign keys between both sides of a many to many relations.

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#remove_inverse_keys(meta) ⇒ Object

Update the inverse keys on destroy.

Examples:

Update the inverse keys.

document.remove_inverse_keys()

Parameters:

  • meta (Metadata)

    The document metadata.

Returns:

  • (Object)

    The updated values.

Since:

  • 2.2.1



63
64
65
# File 'lib/mongoid/relations/synchronization.rb', line 63

def remove_inverse_keys(meta)
  meta.criteria(send(meta.foreign_key)).pull(meta.inverse_foreign_key, id)
end

#syncable?(metadata) ⇒ true, false

Is the document able to be synced on the inverse side? This is only if the key has changed and the relation bindings have not been run.

Examples:

Are the foreign keys syncable?

document.syncable?()

Parameters:

  • metadata (Metadata)

    The relation metadata.

Returns:

  • (true, false)

    If we can sync.

Since:

  • 2.1.0



21
22
23
# File 'lib/mongoid/relations/synchronization.rb', line 21

def syncable?()
  !synced?(.foreign_key) && send(.foreign_key_check)
end

#syncedHash

Get the synced foreign keys.

Examples:

Get the synced foreign keys.

document.synced

Returns:

  • (Hash)

    The synced foreign keys.

Since:

  • 2.1.0



33
34
35
# File 'lib/mongoid/relations/synchronization.rb', line 33

def synced
  @synced ||= {}
end

#synced?(foreign_key) ⇒ true, false

TODO:

Change the sync to be key based.

Has the document been synced for the foreign key?

Examples:

Has the document been synced?

document.synced?

Parameters:

  • foreign_key (String)

    The foreign key.

Returns:

  • (true, false)

    If we can sync.

Since:

  • 2.1.0



49
50
51
# File 'lib/mongoid/relations/synchronization.rb', line 49

def synced?(foreign_key)
  !!synced[foreign_key]
end

#update_inverse_keys(meta) ⇒ Object

Update the inverse keys for the relation.

Examples:

Update the inverse keys

document.update_inverse_keys()

Parameters:

  • meta (Metadata)

    The document metadata.

Returns:

  • (Object)

    The updated values.

Since:

  • 2.1.0



77
78
79
80
81
82
83
# File 'lib/mongoid/relations/synchronization.rb', line 77

def update_inverse_keys(meta)
  return unless changes.has_key?(meta.foreign_key)
  old, new = changes[meta.foreign_key]
  adds, subs = new - (old || []), (old || []) - new
  meta.criteria(adds).add_to_set(meta.inverse_foreign_key, id) unless adds.empty?
  meta.criteria(subs).pull(meta.inverse_foreign_key, id) unless subs.empty?
end