Class: Mongoid::Relations::Referenced::Many

Inherits:
Many
  • Object
show all
Defined in:
build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb

Overview

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

Direct Known Subclasses

ManyToMany

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,
  :as,
  :autosave,
  :before_add,
  :before_remove,
  :dependent,
  :foreign_key,
  :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

#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

#initialize(base, target, metadata) ⇒ Many

Instantiate a new references_many relation. Will set the foreign key and the base on the inverse object.

Examples:

Create the new relation.

Referenced::Many.new(base, target, )

Parameters:

  • base (Document)

    The document this relation hangs off of.

  • target (Array<Document>)

    The target of the relation.

  • metadata (Metadata)

    The relation’s metadata.

Since:

  • 2.0.0.beta.1



233
234
235
236
237
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 233

def initialize(base, target, )
  init(base, Targets::Enumerable.new(target), ) do
    raise_mixed if klass.embedded? && !klass.cyclic?
  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.

Since:

  • 2.0.0.beta.1



457
458
459
460
461
462
463
464
465
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 457

def method_missing(name, *args, &block)
  if target.respond_to?(name)
    target.send(name, *args, &block)
  else
    klass.send(:with_scope, criteria) do
      criteria.public_send(name, *args, &block)
    end
  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.

Referenced::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 new builder object.

Since:

  • 2.0.0.rc.1



592
593
594
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 592

def builder(base, meta, object)
  Builders::Referenced::Many.new(base, meta, object || [])
end

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

Get the standard criteria used for querying this relation.

Examples:

Get the criteria.

Proxy.criteria(meta, id, Model)

Parameters:

  • metadata (Metadata)

    The metadata.

  • object (Object)

    The value of the foreign key.

  • type (Class) (defaults to: nil)

    The optional type.

Returns:

Since:

  • 2.1.0



608
609
610
611
612
613
614
615
616
617
618
619
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 608

def criteria(, object, type = nil)
  apply_ordering(
    with_inverse_field_criterion(
      with_polymorphic_criterion(
        .klass.where(.foreign_key => object),
        ,
        type
      ),
      
    ), 
  )
end

.eager_load_klassObject



621
622
623
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 621

def eager_load_klass
  Relations::Eager::HasMany
end

.embedded?false

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

Examples:

Is this relation embedded?

Referenced::Many.embedded?

Returns:

  • (false)

    Always false.

Since:

  • 2.0.0.rc.1



634
635
636
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 634

def embedded?
  false
end

.foreign_key(name) ⇒ String

Get the foreign key for the provided name.

Examples:

Get the foreign key.

Referenced::Many.foreign_key(:person)

Parameters:

Returns:

  • (String)

    The foreign key.

Since:

  • 3.0.0



648
649
650
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 648

def foreign_key(name)
  "#{name}#{foreign_key_suffix}"
end

.foreign_key_defaultnil

Get the default value for the foreign key.

Examples:

Get the default.

Referenced::Many.foreign_key_default

Returns:

  • (nil)

    Always nil.

Since:

  • 2.0.0.rc.1



660
661
662
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 660

def foreign_key_default
  nil
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::Many.foreign_key_suffix

Returns:

  • (String)

    “_id”

Since:

  • 2.0.0.rc.1



672
673
674
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 672

def foreign_key_suffix
  "_id"
end

.macroSymbol

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

Examples:

Get the macro.

Referenced::Many.macro

Returns:



683
684
685
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 683

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



709
710
711
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 709

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



723
724
725
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 723

def path(document)
  Mongoid::Atomic::Paths::Root.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?

Referenced::Many.stores_foreign_key?

Returns:

  • (false)

    Always false.

Since:

  • 2.0.0.rc.1



736
737
738
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 736

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



748
749
750
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 748

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



761
762
763
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 761

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



48
49
50
51
52
53
54
55
56
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 48

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

#build(attributes = {}, options = {}, 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 = {}, options = {}, type = nil) ⇒ Document

    Parameters:

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

      The attributes of the new document.

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

      The scoped assignment options.

    • 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



99
100
101
102
103
104
105
106
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 99

def build(attributes = {}, type = nil)
  doc = Factory.build(type || klass, attributes)
  append(doc)
  doc.apply_post_processed_defaults
  yield(doc) if block_given?
  doc.run_callbacks(:build) { doc }
  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
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 70

def concat(documents)
  docs, inserts = [], []
  documents.each do |doc|
    next unless doc
    append(doc)
    save_or_delay(doc, docs, inserts) if persistable?
  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



121
122
123
124
125
126
127
128
129
130
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 121

def delete(document)
  execute_callback :before_remove, document
  target.delete(document) do |doc|
    if doc
      unbind_one(doc)
      cascade!(doc) if !_assigning?
    end
    execute_callback :after_remove, doc
  end
end

#delete_all(conditions = nil) ⇒ Integer

Deletes all related documents from the database given the supplied conditions.

Examples:

Delete all documents in the relation.

person.posts.delete_all

Conditonally delete all documents in the relation.

person.posts.delete_all({ :title => "Testing" })

Parameters:

  • conditions (Hash) (defaults to: nil)

    Optional conditions to delete with.

Returns:

  • (Integer)

    The number of documents deleted.

Since:

  • 2.0.0.beta.1



146
147
148
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 146

def delete_all(conditions = nil)
  remove_all(conditions, :delete_all)
end

#destroy_all(conditions = nil) ⇒ Integer

Destroys all related documents from the database given the supplied conditions.

Examples:

Destroy all documents in the relation.

person.posts.destroy_all

Conditonally destroy all documents in the relation.

person.posts.destroy_all({ :title => "Testing" })

Parameters:

  • conditions (Hash) (defaults to: nil)

    Optional conditions to destroy with.

Returns:

  • (Integer)

    The number of documents destroyd.

Since:

  • 2.0.0.beta.1



164
165
166
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 164

def destroy_all(conditions = nil)
  remove_all(conditions, :destroy_all)
end

#eachArray<Document>

Note:

This will load the entire relation into memory.

Iterate over each document in the relation and yield to the provided block.

Examples:

Iterate over the documents.

person.posts.each do |post|
  post.save
end

Returns:

  • (Array<Document>)

    The loaded docs.

Since:

  • 2.1.0



181
182
183
184
185
186
187
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 181

def each
  if block_given?
    target.each { |doc| yield(doc) }
  else
    to_enum
  end
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.



195
196
197
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 195

def exists?
  criteria.exists?
end

#find(*args) ⇒ Document, Criteria

Note:

This will keep matching documents in memory for iteration later.

Find the matchind document on the association, either based on id or conditions.

Examples:

Find by an id.

person.posts.find(BSON::ObjectId.new)

Find by multiple ids.

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

Parameters:

Returns:

Since:

  • 2.0.0.beta.1



216
217
218
219
220
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 216

def find(*args)
  matching = criteria.find(*args)
  Array(matching).each { |doc| target.push(doc) }
  matching
end

#nullifyObject Also known as: nullify_all

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.posts.nullify

Since:

  • 2.0.0.rc.1



247
248
249
250
251
252
253
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 247

def nullify
  criteria.update_all(foreign_key => nil)
  target.clear do |doc|
    unbind_one(doc)
    doc.changed_attributes.delete(foreign_key)
  end
end

#purgeMany Also known as: clear

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

Examples:

Clear the relation.

person.posts.clear

Returns:

  • (Many)

    The relation emptied.

Since:

  • 2.0.0.beta.1



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 265

def purge
  unless .destructive?
    nullify
  else
    after_remove_error = nil
    criteria.delete_all
    many = target.clear do |doc|
      execute_callback :before_remove, doc
      unbind_one(doc)
      doc.destroyed = true
      begin
        execute_callback :after_remove, doc
      rescue => e
        after_remove_error = e
      end
    end
    raise after_remove_error if after_remove_error
    many
  end
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.

Examples:

Replace the relation.

person.posts.substitute([ new_post ])

Parameters:

  • replacement (Array<Document>)

    The replacement target.

Returns:

  • (Many)

    The relation.

Since:

  • 2.0.0.rc.1



299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 299

def substitute(replacement)
  if replacement
    new_docs, docs = replacement.compact, []
    new_ids = new_docs.map { |doc| doc._id }
    remove_not_in(new_ids)
    new_docs.each do |doc|
      docs.push(doc) if doc.send(foreign_key) != base._id
    end
    concat(docs)
  else
    purge
  end
  self
end

#unscopedCriteria

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

Examples:

Get the unscoped criteria.

person.posts.unscoped

Returns:

Since:

  • 2.4.0



323
324
325
326
327
# File 'build/mongoid-6.1/lib/mongoid/relations/referenced/many.rb', line 323

def unscoped
  klass.unscoped.where(
    foreign_key => Conversions.flag(base._id, )
  )
end