Class: Mongoid::Relations::Embedded::Many

Inherits:
Many
  • Object
show all
Includes:
Batchable
Defined in:
lib/mongoid/relations/embedded/many.rb

Overview

This class handles the behaviour for a document that embeds many other documents within in it as an array.

Instance Attribute Summary

Attributes inherited from Proxy

#base, #loaded, #metadata, #target

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Batchable

#batch_clear, #batch_insert, #batch_remove, #batch_replace

Methods included from Atomic::Positionable

#positionally

Methods inherited from Many

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

Methods inherited from Proxy

apply_ordering, eager_load_ids, #init, #klass, #reset_unloaded, #substitutable, #with

Methods included from Marshalable

#marshal_dump, #marshal_load

Constructor Details

#initialize(base, target, metadata) ⇒ Many

Instantiate a new embeds_many relation.

Examples:

Create the new relation.

Many.new(person, addresses, )

Parameters:

  • base (Document)

    The document this relation hangs off of.

  • target (Array<Document>)

    The child documents of the relation.

  • metadata (Metadata)

    The relation’s metadata



253
254
255
256
257
258
259
260
261
262
# File 'lib/mongoid/relations/embedded/many.rb', line 253

def initialize(base, target, )
  init(base, target, ) do
    target.each_with_index do |doc, index|
      integrate(doc)
      doc._index = index
    end
    @_unscoped = target.dup
    @target = scope(target)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Criteria, Object (private)

If the target array does not respond to the supplied method then try to find a named scope or criteria on the class and send the call there.

If the method exists on the array, use the default proxy behavior.

Parameters:

  • name (Symbol, String)

    The name of the method.

  • args (Array)

    The method args

  • block (Proc)

    Optional block to pass.

Returns:

  • (Criteria, Object)

    A Criteria or return value from the target.



421
422
423
424
425
426
# File 'lib/mongoid/relations/embedded/many.rb', line 421

def method_missing(name, *args, &block)
  return super if target.respond_to?(name)
  klass.send(:with_scope, criteria) do
    criteria.send(name, *args, &block)
  end
end

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.

Embedded::Many.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 newly instantiated builder object.

Since:

  • 2.0.0.rc.1



532
533
534
# File 'lib/mongoid/relations/embedded/many.rb', line 532

def builder(base, meta, object)
  Builders::Embedded::Many.new(base, meta, object)
end

.embedded?true

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

Examples:

Is the relation embedded?

Embedded::Many.embedded?

Returns:

  • (true)

    true.

Since:

  • 2.0.0.rc.1



545
546
547
# File 'lib/mongoid/relations/embedded/many.rb', line 545

def embedded?
  true
end

.foreign_key_suffixnil

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

Examples:

Get the suffix for the foreign key.

Referenced::Many.foreign_key_suffix

Returns:

  • (nil)

    nil.

Since:

  • 3.0.0



557
558
559
# File 'lib/mongoid/relations/embedded/many.rb', line 557

def foreign_key_suffix
  nil
end

.macroSymbol

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

Examples:

Get the relation macro.

Mongoid::Relations::Embedded::Many.macro

Returns:

Since:

  • 2.0.0.rc.1



570
571
572
# File 'lib/mongoid/relations/embedded/many.rb', line 570

def macro
  :embeds_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.

NestedAttributes::Many.builder(attributes, options)

Parameters:

  • metadata (Metadata)

    The relation metadata.

  • attributes (Hash)

    The attributes to build with.

  • options (Hash)

    The builder options.

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:

Since:

  • 2.0.0.rc.1



596
597
598
# File 'lib/mongoid/relations/embedded/many.rb', line 596

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

.path(document) ⇒ Mongoid::Atomic::Paths::Embedded::Many

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:

Since:

  • 2.1.0



611
612
613
# File 'lib/mongoid/relations/embedded/many.rb', line 611

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

.stores_foreign_key?false

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?

Embedded::Many.stores_foreign_key?

Returns:

  • (false)

    false.

Since:

  • 2.0.0.rc.1



624
625
626
# File 'lib/mongoid/relations/embedded/many.rb', line 624

def stores_foreign_key?
  false
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



636
637
638
639
640
641
# File 'lib/mongoid/relations/embedded/many.rb', line 636

def valid_options
  [
    :as, :cascade_callbacks, :cyclic, :order, :versioned, :store_as,
    :before_add, :after_add, :before_remove, :after_remove
  ]
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



652
653
654
# File 'lib/mongoid/relations/embedded/many.rb', line 652

def validation_default
  true
end

Instance Method Details

#<<(*args) ⇒ Object 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.addresses << address

Push a document.

person.addresses.push(address)

Parameters:



23
24
25
26
27
28
29
30
31
# File 'lib/mongoid/relations/embedded/many.rb', line 23

def <<(*args)
  docs = args.flatten
  return concat(docs) if docs.size > 1
  if doc = docs.first
    append(doc)
    doc.save if persistable? && !_assigning?
  end
  self
end

#as_documentArray<Hash>

Get this relation as as its representation in the database.

Examples:

Convert the relation to an attributes hash.

person.addresses.as_document

Returns:

  • (Array<Hash>)

    The relation as stored in the db.

Since:

  • 2.0.0.rc.1



42
43
44
45
46
47
48
# File 'lib/mongoid/relations/embedded/many.rb', line 42

def as_document
  attributes = []
  _unscoped.each do |doc|
    attributes.push(doc.as_document)
  end
  attributes
end

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

Builds a new document in the relation and appends it to the target. Takes an optional type if you want to specify a subclass.

Examples:

Build a new document on the relation.

person.people.build(:name => "Bozo")

Overloads:

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

    Parameters:

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

      The attributes to build the document with.

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

      The scoped assignment options.

    • type (Class) (defaults to: nil)

      Optional class to build the document with.

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

    Parameters:

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

      The attributes to build the document with.

    • type (Class) (defaults to: nil)

      Optional class to build the document with.

Yields:

  • (doc)

Returns:



82
83
84
85
86
87
88
89
90
91
92
# File 'lib/mongoid/relations/embedded/many.rb', line 82

def build(attributes = {}, options = {}, type = nil)
  if options.is_a?(Class)
    options, type = {}, options
  end
  doc = Factory.build(type || .klass, attributes, options)
  append(doc)
  doc.apply_post_processed_defaults
  yield(doc) if block_given?
  doc.run_callbacks(:build) { doc }
  doc
end

#clearMany

Clear the relation. Will delete the documents from the db if they are already persisted.

Examples:

Clear the relation.

person.addresses.clear

Returns:

  • (Many)

    The empty relation.



102
103
104
105
# File 'lib/mongoid/relations/embedded/many.rb', line 102

def clear
  batch_clear(target.dup)
  self
end

#concat(docs) ⇒ 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.addresses.concat([ address_one, address_two ])

Parameters:

  • docs (Array<Document>)

    The docs to add.

Returns:

Since:

  • 2.4.0



61
62
63
64
# File 'lib/mongoid/relations/embedded/many.rb', line 61

def concat(docs)
  batch_insert(docs) unless docs.empty?
  self
end

#countInteger

Returns a count of the number of documents in the association that have actually been persisted to the database.

Use #size if you want the total number of documents.

Examples:

Get the count of persisted documents.

person.addresses.count

Returns:

  • (Integer)

    The total number of persisted embedded docs, as flagged by the #persisted? method.



117
118
119
# File 'lib/mongoid/relations/embedded/many.rb', line 117

def count
  target.select { |doc| doc.persisted? }.size
end

#delete(document) ⇒ Document?

Delete the supplied document from the target. This method is proxied in order to reindex the array after the operation occurs.

Examples:

Delete the document from the relation.

person.addresses.delete(address)

Parameters:

  • document (Document)

    The document to be deleted.

Returns:

  • (Document, nil)

    The deleted document or nil if nothing deleted.

Since:

  • 2.0.0.rc.1



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/mongoid/relations/embedded/many.rb', line 132

def delete(document)
  execute_callback :before_remove, document
  doc = target.delete_one(document)
  if doc && !_binding?
    _unscoped.delete_one(doc) unless doc.paranoid?
    if _assigning?
      if doc.paranoid?
        doc.destroy(suppress: true)
      else
        base.add_atomic_pull(doc)
      end
    else
      doc.delete(suppress: true)
      unbind_one(doc)
    end
  end
  reindex
  execute_callback :after_remove, document
  doc
end

#delete_all(conditions = {}) ⇒ Integer

Delete all the documents in the association without running callbacks.

Examples:

Delete all documents from the relation.

person.addresses.delete_all

Conditionally delete documents from the relation.

person.addresses.delete_all({ :street => "Bond" })

Parameters:

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

    Conditions on which documents to delete.

Returns:

  • (Integer)

    The number of documents deleted.



176
177
178
# File 'lib/mongoid/relations/embedded/many.rb', line 176

def delete_all(conditions = {})
  remove_all(conditions, :delete)
end

#delete_ifMany, Enumerator

Delete all the documents for which the provided block returns true.

Examples:

Delete the matching documents.

person.addresses.delete_if do |doc|
  doc.state = "GA"
end

Returns:

  • (Many, Enumerator)

    The relation or an enumerator if no block was provided.

Since:

  • 3.1.0



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

def delete_if
  if block_given?
    target.each do |doc|
      delete(doc) if yield(doc)
    end
    self
  else
    super
  end
end

#deletedCriteria

For use only with Mongoid::Paranoia - will be removed in 4.0.

Examples:

Get the deleted documents from the relation.

person.paranoid_phones.deleted

Returns:

Since:

  • 3.0.10



161
162
163
# File 'lib/mongoid/relations/embedded/many.rb', line 161

def deleted
  unscoped.deleted
end

#destroy_all(conditions = {}) ⇒ Integer

Destroy all the documents in the association whilst running callbacks.

Examples:

Destroy all documents from the relation.

person.addresses.destroy_all

Conditionally destroy documents from the relation.

person.addresses.destroy_all({ :street => "Bond" })

Parameters:

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

    Conditions on which documents to destroy.

Returns:

  • (Integer)

    The number of documents destroyed.



213
214
215
# File 'lib/mongoid/relations/embedded/many.rb', line 213

def destroy_all(conditions = {})
  remove_all(conditions, :destroy)
end

#exists?true, false

Determine if any documents in this relation exist in the database.

Examples:

Are there persisted documents?

person.posts.exists?

Returns:

  • (true, false)

    True is persisted documents exist, false if not.



223
224
225
# File 'lib/mongoid/relations/embedded/many.rb', line 223

def exists?
  count > 0
end

#find(*args) ⇒ Array<Document>, Document

Finds a document in this association through several different methods.

Examples:

Find a document by its id.

person.addresses.find(Moped::BSON::ObjectId.new)

Find documents for multiple ids.

person.addresses.find([ Moped::BSON::ObjectId.new, Moped::BSON::ObjectId.new ])

Parameters:

  • args (Array<Object>)

    Various arguments.

Returns:



239
240
241
# File 'lib/mongoid/relations/embedded/many.rb', line 239

def find(*args)
  criteria.find(*args)
end

#in_memoryArray<Document>

Get all the documents in the relation that are loaded into memory.

Examples:

Get the in memory documents.

relation.in_memory

Returns:

  • (Array<Document>)

    The documents in memory.

Since:

  • 2.1.0



272
273
274
# File 'lib/mongoid/relations/embedded/many.rb', line 272

def in_memory
  target
end

#pop(count = nil) ⇒ Document+

Pop documents off the relation. This can be a single document or multiples, and will automatically persist the changes.

Examples:

Pop a single document.

relation.pop

Pop multiple documents.

relation.pop(3)

Parameters:

  • count (Integer) (defaults to: nil)

    The number of documents to pop, or 1 if not provided.

Returns:

Since:

  • 3.0.0



291
292
293
294
295
296
297
298
299
# File 'lib/mongoid/relations/embedded/many.rb', line 291

def pop(count = nil)
  if count
    if docs = target[target.size - count, target.size]
      docs.each { |doc| delete(doc) }
    end
  else
    delete(target[-1])
  end
end

#substitute(docs) ⇒ Many

Substitutes the supplied target documents for the existing documents in the relation.

Examples:

Substitute the relation’s target.

person.addresses.substitute([ address ])

Parameters:

  • docs (Array<Document>)

    The replacement docs.

Returns:

  • (Many)

    The proxied relation.

Since:

  • 2.0.0.rc.1



312
313
314
315
# File 'lib/mongoid/relations/embedded/many.rb', line 312

def substitute(docs)
  batch_replace(docs)
  self
end

#unscopedCriteria

Return the relation with all previous scoping removed. This is the exact representation of the docs in the database.

Examples:

Get the unscoped documents.

person.addresses.unscoped

Returns:

Since:

  • 2.4.0



326
327
328
329
330
331
# File 'lib/mongoid/relations/embedded/many.rb', line 326

def unscoped
  criterion = klass.unscoped
  criterion.embedded = true
  criterion.documents = _unscoped.delete_if(&:marked_for_destruction?)
  criterion
end