Class: Mongoid::Association::Referenced::HasAndBelongsToMany::Binding

Inherits:
Object
  • Object
show all
Includes:
Bindable
Defined in:
build/mongoid-7.0/lib/mongoid/association/referenced/has_and_belongs_to_many/binding.rb

Overview

Binding class for all has_and_belongs_to_many relations.

Since:

  • 7.0

Instance Attribute Summary

Attributes included from Bindable

#_association, #_base, #_target

Instance Method Summary collapse

Methods included from Bindable

#binding, #initialize

Instance Method Details

#bind_one(doc) ⇒ Object

Binds a single document with the inverse relation. Used specifically when appending to the proxy.

Examples:

Bind one document.

person.preferences.bind_one(preference)

Parameters:

  • doc (Document)

    The single document to bind.

Since:

  • 2.0.0.rc.1



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'build/mongoid-7.0/lib/mongoid/association/referenced/has_and_belongs_to_many/binding.rb', line 20

def bind_one(doc)
  binding do
    inverse_keys = doc.you_must(_association.inverse_foreign_key)
    if inverse_keys
      record_id = inverse_record_id(doc)
      unless inverse_keys.include?(record_id)
        doc.you_must(_association.inverse_foreign_key_setter, inverse_keys.push(record_id))
      end
      doc.reset_relation_criteria(_association.inverse)
    end
    _base._synced[_association.foreign_key] = true
    doc._synced[_association.inverse_foreign_key] = true
  end
end

#determine_inverse_association(doc) ⇒ Object

Since:

  • 7.0



64
65
66
# File 'build/mongoid-7.0/lib/mongoid/association/referenced/has_and_belongs_to_many/binding.rb', line 64

def determine_inverse_association(doc)
  doc.relations[_base.class.name.demodulize.underscore.pluralize]
end

#inverse_record_id(doc) ⇒ Object

Find the inverse id referenced by inverse_keys

Since:

  • 7.0



55
56
57
58
59
60
61
62
# File 'build/mongoid-7.0/lib/mongoid/association/referenced/has_and_belongs_to_many/binding.rb', line 55

def inverse_record_id(doc)
  inverse_association = determine_inverse_association(doc)
  if inverse_association
    _base.__send__(inverse_association.primary_key)
  else
    _base._id
  end
end

#unbind_one(doc) ⇒ Object

Unbind a single document.

Examples:

Unbind the document.

person.preferences.unbind_one(document)

Since:

  • 2.0.0.rc.1



41
42
43
44
45
46
47
48
49
50
51
52
# File 'build/mongoid-7.0/lib/mongoid/association/referenced/has_and_belongs_to_many/binding.rb', line 41

def unbind_one(doc)
  binding do
    _base.send(_association.foreign_key).delete_one(record_id(doc))
    inverse_keys = doc.you_must(_association.inverse_foreign_key)
    if inverse_keys
      inverse_keys.delete_one(inverse_record_id(doc))
      doc.reset_relation_criteria(_association.inverse)
    end
    _base._synced[_association.foreign_key] = true
    doc._synced[_association.inverse_foreign_key] = true
  end
end