Class: Mongoid::Relations::Referenced::ManyToMany

Inherits:
Many
  • Object
show all
Defined in:
lib/mongoid/relations/referenced/many_to_many.rb

Overview

This class defines the behaviour for all relations that are a many-to-many between documents in different collections.

Constant Summary collapse

VALID_OPTIONS =

The allowed options when defining this relation.

Returns:

  • (Array<Symbol>)

    The allowed options when defining this relation.

Since:

  • 6.0.0

[
  :after_add,
  :after_remove,
  :autosave,
  :before_add,
  :before_remove,
  :dependent,
  :foreign_key,
  :index,
  :order,
  :primary_key
].freeze

Instance Attribute Summary

Attributes inherited from Proxy

#__metadata, #base, #target

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Many

#delete_all, #destroy_all, #each, #exists?, #find, #initialize

Methods inherited from Many

#blank?, #create, #create!, #find_or_create_by, #find_or_create_by!, #find_or_initialize_by, #nil?, #respond_to?, #scoped, #serializable_hash

Methods inherited from Proxy

apply_ordering, #extend_proxies, #init, #klass, #reset_unloaded, #substitutable

Methods included from Marshalable

#marshal_dump, #marshal_load

Constructor Details

This class inherits a constructor from Mongoid::Relations::Referenced::Many

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Mongoid::Relations::Referenced::Many

Class Method Details

.builder(base, meta, object) ⇒ Builder

Return the builder that is responsible for generating the documents that will be used by this relation.

Examples:

Get the builder.

Referenced::ManyToMany.builder(meta, object)

Parameters:

  • base (Document)

    The base document.

  • meta (Metadata)

    The metadata of the relation.

  • object (Document, Hash)

    A document or attributes to build with.

Returns:

  • (Builder)

    A new builder object.

Since:

  • 2.0.0.rc.1



307
308
309
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 307

def builder(base, meta, object)
  Builders::Referenced::ManyToMany.new(base, meta, object)
end

.criteria(metadata, object, type = nil) ⇒ Criteria

Create the standard criteria for this relation given the supplied metadata and object.

Examples:

Get the criteria.

Proxy.criteria(meta, object)

Parameters:

  • metadata (Metadata)

    The relation metadata.

  • object (Object)

    The object for the criteria.

  • type (Class) (defaults to: nil)

    The criteria class.

Returns:

Since:

  • 2.1.0



324
325
326
327
328
329
330
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 324

def criteria(, object, type = nil)
  apply_ordering(
    .klass.all_of(
      .primary_key => { "$in" => object || [] }
    ), 
  )
end

.eager_load_klassObject



332
333
334
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 332

def eager_load_klass
  Relations::Eager::HasAndBelongsToMany
end

.embedded?false

Returns true if the relation is an embedded one. In this case always false.

Examples:

Is this relation embedded?

Referenced::ManyToMany.embedded?

Returns:

  • (false)

    Always false.

Since:

  • 2.0.0.rc.1



345
346
347
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 345

def embedded?
  false
end

.foreign_key(name) ⇒ String

Get the foreign key for the provided name.

Examples:

Get the foreign key.

Referenced::ManyToMany.foreign_key(:person)

Parameters:

Returns:

  • (String)

    The foreign key.

Since:

  • 3.0.0



359
360
361
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 359

def foreign_key(name)
  "#{name.to_s.singularize}#{foreign_key_suffix}"
end

.foreign_key_defaultArray

Get the default value for the foreign key.

Examples:

Get the default.

Referenced::ManyToMany.foreign_key_default

Returns:

  • (Array)

    Always an empty array.

Since:

  • 2.0.0.rc.1



371
372
373
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 371

def foreign_key_default
  []
end

.foreign_key_suffixString

Returns the suffix of the foreign key field, either “_id” or “_ids”.

Examples:

Get the suffix for the foreign key.

Referenced::ManyToMany.foreign_key_suffix

Returns:

  • (String)

    “_ids”

Since:

  • 2.0.0.rc.1



383
384
385
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 383

def foreign_key_suffix
  "_ids"
end

.macroSymbol

Returns the macro for this relation. Used mostly as a helper in reflection.

Examples:

Get the macro.

Referenced::ManyToMany.macro

Returns:

  • (Symbol)

    :has_and_belongs_to_many



394
395
396
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 394

def macro
  :has_and_belongs_to_many
end

.nested_builder(metadata, attributes, options) ⇒ NestedBuilder

Return the nested builder that is responsible for generating the documents that will be used by this relation.

Examples:

Get the nested builder.

Referenced::ManyToMany.builder(attributes, options)

Parameters:

  • metadata (Metadata)

    The relation metadata.

  • attributes (Hash)

    The attributes to build with.

  • options (Hash)

    The options for the builder.

Options Hash (options):

  • :allow_destroy (true, false)

    Can documents be deleted?

  • :limit (Integer)

    Max number of documents to create at once.

  • :reject_if (Proc, Symbol)

    If documents match this option then they are ignored.

  • :update_only (true, false)

    Only existing documents can be modified.

Returns:

  • (NestedBuilder)

    A newly instantiated nested builder object.

Since:

  • 2.0.0.rc.1



420
421
422
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 420

def nested_builder(, attributes, options)
  Builders::NestedAttributes::Many.new(, attributes, options)
end

.path(document) ⇒ Root

Get the path calculator for the supplied document.

Examples:

Get the path calculator.

Proxy.path(document)

Parameters:

  • document (Document)

    The document to calculate on.

Returns:

  • (Root)

    The root atomic path calculator.

Since:

  • 2.1.0



434
435
436
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 434

def path(document)
  Mongoid::Atomic::Paths::Root.new(document)
end

.stores_foreign_key?true

Tells the caller if this relation is one that stores the foreign key on its own objects.

Examples:

Does this relation store a foreign key?

Referenced::Many.stores_foreign_key?

Returns:

  • (true)

    Always true.

Since:

  • 2.0.0.rc.1



447
448
449
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 447

def stores_foreign_key?
  true
end

.valid_optionsArray<Symbol>

Get the valid options allowed with this relation.

Examples:

Get the valid options.

Relation.valid_options

Returns:

  • (Array<Symbol>)

    The valid options.

Since:

  • 2.1.0



459
460
461
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 459

def valid_options
  VALID_OPTIONS
end

.validation_defaulttrue, false

Get the default validation setting for the relation. Determines if by default a validates associated will occur.

Examples:

Get the validation default.

Proxy.validation_default

Returns:

  • (true, false)

    The validation default.

Since:

  • 2.1.9



472
473
474
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 472

def validation_default
  true
end

Instance Method Details

#<<(*args) ⇒ Array<Document> Also known as: push

Appends a document or array of documents to the relation. Will set the parent and update the index in the process.

Examples:

Append a document.

person.posts << post

Push a document.

person.posts.push(post)

Concat with other documents.

person.posts.concat([ post_one, post_two ])

Parameters:

Returns:

  • (Array<Document>)

    The loaded docs.

Since:

  • 2.0.0.beta.1



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 45

def <<(*args)
  docs = args.flatten
  return concat(docs) if docs.size > 1
  if doc = docs.first
    append(doc)
    base.add_to_set(foreign_key => doc.send(.primary_key))
    if child_persistable?(doc)
      doc.save
    end
  end
  unsynced(base, foreign_key) and self
end

#build(attributes = {}, type = nil) ⇒ Document #build(attributes = {}, type = nil) ⇒ Document Also known as: new

Build a new document from the attributes and append it to this relation without saving.

Examples:

Build a new document on the relation.

person.posts.build(:title => "A new post")

Overloads:

  • #build(attributes = {}, type = nil) ⇒ Document

    Parameters:

    • attributes (Hash) (defaults to: {})

      The attributes of the new document.

    • type (Class) (defaults to: nil)

      The optional subclass to build.

  • #build(attributes = {}, type = nil) ⇒ Document

    Parameters:

    • attributes (Hash) (defaults to: {})

      The attributes of the new document.

    • type (Class) (defaults to: nil)

      The optional subclass to build.

Yields:

  • (doc)

Returns:

Since:

  • 2.0.0.beta.1



109
110
111
112
113
114
115
116
117
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 109

def build(attributes = {}, type = nil)
  doc = Factory.build(type || klass, attributes)
  base.send(foreign_key).push(doc._id)
  append(doc)
  doc.apply_post_processed_defaults
  unsynced(doc, inverse_foreign_key)
  yield(doc) if block_given?
  doc
end

#concat(documents) ⇒ Array<Document>

Appends an array of documents to the relation. Performs a batch insert of the documents instead of persisting one at a time.

Examples:

Concat with other documents.

person.posts.concat([ post_one, post_two ])

Parameters:

  • documents (Array<Document>)

    The docs to add.

Returns:

Since:

  • 2.4.0



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 70

def concat(documents)
  ids, docs, inserts = {}, [], []
  documents.each do |doc|
    next unless doc
    append(doc)
    if persistable? || _creating?
      ids[doc._id] = true
      save_or_delay(doc, docs, inserts)
    else
      existing = base.send(foreign_key)
      unless existing.include?(doc._id)
        existing.push(doc._id) and unsynced(base, foreign_key)
      end
    end
  end
  if persistable? || _creating?
    base.push(foreign_key => ids.keys)
  end
  persist_delayed(docs, inserts)
  self
end

#delete(document) ⇒ Document

Delete the document from the relation. This will set the foreign key on the document to nil. If the dependent options on the relation are :delete or :destroy the appropriate removal will occur.

Examples:

Delete the document.

person.posts.delete(post)

Parameters:

  • document (Document)

    The document to remove.

Returns:

Since:

  • 2.1.0



132
133
134
135
136
137
138
139
140
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 132

def delete(document)
  doc = super
  if doc && persistable?
    base.pull(foreign_key => doc.send(.primary_key))
    target._unloaded = criteria
    unsynced(base, foreign_key)
  end
  doc
end

#nullifyObject Also known as: nullify_all, clear, purge

Removes all associations between the base document and the target documents by deleting the foreign keys and the references, orphaning the target documents in the process.

Examples:

Nullify the relation.

person.preferences.nullify

Since:

  • 2.0.0.rc.1



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 150

def nullify
  target.each do |doc|
    execute_callback :before_remove, doc
  end
  unless .forced_nil_inverse?
    criteria.pull(inverse_foreign_key => base._id)
  end
  if persistable?
    base.set(foreign_key => base.send(foreign_key).clear)
  end
  after_remove_error = nil
  many_to_many = target.clear do |doc|
    unbind_one(doc)
    unless .forced_nil_inverse?
      doc.changed_attributes.delete(inverse_foreign_key)
    end
    begin
      execute_callback :after_remove, doc
    rescue => e
      after_remove_error = e
    end
  end
  raise after_remove_error if after_remove_error
  many_to_many
end

#substitute(replacement) ⇒ Many

Substitutes the supplied target documents for the existing documents in the relation. If the new target is nil, perform the necessary deletion.

person.preferences.substitute([ new_post ])

Examples:

Replace the relation.

Parameters:

  • replacement (Array<Document>)

    The replacement target.

Returns:

  • (Many)

    The relation.

Since:

  • 2.0.0.rc.1



191
192
193
194
195
196
197
198
199
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 191

def substitute(replacement)
  purge
  unless replacement.blank?
    push(replacement.compact.uniq)
  else
    reset_unloaded
  end
  self
end

#unscopedCriteria

Get a criteria for the documents without the default scoping applied.

Examples:

Get the unscoped criteria.

person.preferences.unscoped

Returns:

Since:

  • 2.4.0



210
211
212
# File 'lib/mongoid/relations/referenced/many_to_many.rb', line 210

def unscoped
  klass.unscoped.any_in(_id: base.send(foreign_key))
end