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

Inherits:
Many show all
Includes:
Batch
Defined in:
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

Instance Attribute Summary

Attributes inherited from Proxy

#base, #loaded, #metadata, #target

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Many

#blank?, #exists?, #find_or_create_by, #find_or_initialize_by, #nil?, #respond_to?, #scoped, #serializable_hash

Methods inherited from Proxy

#init, #substitutable

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



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

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

Since:

  • 2.0.0.beta.1



392
393
394
395
396
397
398
399
400
# File 'lib/mongoid/relations/referenced/many.rb', line 392

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

Class Method Details

.builder(meta, object, loading = false) ⇒ 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:

  • 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



455
456
457
# File 'lib/mongoid/relations/referenced/many.rb', line 455

def builder(meta, object, loading = false)
  Builders::Referenced::Many.new(meta, object || [], loading)
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



471
472
473
# File 'lib/mongoid/relations/referenced/many.rb', line 471

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

.eager_load(metadata, criteria) ⇒ Criteria

Eager load the relation based on the criteria.

Examples:

Eager load the criteria.

Proxy.eager_load(, criteria)

Parameters:

  • metadata (Metadata)

    The relation metadata.

  • criteria (Criteria)

    The criteria being used.

Returns:

  • (Criteria)

    The criteria to eager load the relation.

Since:

  • 2.2.0



486
487
488
489
490
491
# File 'lib/mongoid/relations/referenced/many.rb', line 486

def eager_load(, criteria)
  klass, foreign_key = .klass, .foreign_key
  klass.any_in(foreign_key => criteria.load_ids("_id").uniq).each do |doc|
    IdentityMap.set_many(doc, foreign_key => doc.send(foreign_key))
  end
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



502
503
504
# File 'lib/mongoid/relations/referenced/many.rb', line 502

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



514
515
516
# File 'lib/mongoid/relations/referenced/many.rb', line 514

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:

Since:

  • 2.0.0.rc.1



526
527
528
# File 'lib/mongoid/relations/referenced/many.rb', line 526

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:

  • (Symbol)

    :references_many



537
538
539
# File 'lib/mongoid/relations/referenced/many.rb', line 537

def macro
  :references_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



563
564
565
# File 'lib/mongoid/relations/referenced/many.rb', line 563

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



577
578
579
# File 'lib/mongoid/relations/referenced/many.rb', line 577

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



590
591
592
# File 'lib/mongoid/relations/referenced/many.rb', line 590

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:

Since:

  • 2.1.0



602
603
604
# File 'lib/mongoid/relations/referenced/many.rb', line 602

def valid_options
  [ :as, :autosave, :dependent, :foreign_key, :order ]
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



615
616
617
# File 'lib/mongoid/relations/referenced/many.rb', line 615

def validation_default
  true
end

Instance Method Details

#<<(*args) ⇒ Array<Document> Also known as: concat, 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:

Since:

  • 2.0.0.beta.1



31
32
33
34
35
36
37
38
39
# File 'lib/mongoid/relations/referenced/many.rb', line 31

def <<(*args)
  batched do
    args.flatten.each do |doc|
      next unless doc
      append(doc)
      doc.save if persistable? && !doc.validated?
    end
  end
end

#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")

Parameters:

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

    The attributes of the new document.

  • type (Class) (defaults to: nil)

    The optional subclass to build.

Returns:

Since:

  • 2.0.0.beta.1



55
56
57
58
59
60
# File 'lib/mongoid/relations/referenced/many.rb', line 55

def build(attributes = {}, type = nil)
  Factory.build(type || klass, attributes).tap do |doc|
    append(doc)
    yield(doc) if block_given?
  end
end

#create(attributes = nil, type = nil, &block) ⇒ Document

Creates a new document on the references many relation. This will save the document if the parent has been persisted.

Examples:

Create and save the new document.

person.posts.create(:text => "Testing")

Parameters:

  • attributes (Hash) (defaults to: nil)

    The attributes to create with.

  • type (Class) (defaults to: nil)

    The optional type of document to create.

Returns:

  • (Document)

    The newly created document.

Since:

  • 2.0.0.beta.1



75
76
77
78
79
# File 'lib/mongoid/relations/referenced/many.rb', line 75

def create(attributes = nil, type = nil, &block)
  build(attributes, type, &block).tap do |doc|
    base.persisted? ? doc.save : raise_unsaved(doc)
  end
end

#create!(attributes = nil, type = nil, &block) ⇒ Document

Creates a new document on the references many relation. This will save the document if the parent has been persisted and will raise an error if validation fails.

Examples:

Create and save the new document.

person.posts.create!(:text => "Testing")

Parameters:

  • attributes (Hash) (defaults to: nil)

    The attributes to create with.

  • type (Class) (defaults to: nil)

    The optional type of document to create.

Returns:

  • (Document)

    The newly created document.

Raises:

Since:

  • 2.0.0.beta.1



96
97
98
99
100
# File 'lib/mongoid/relations/referenced/many.rb', line 96

def create!(attributes = nil, type = nil, &block)
  build(attributes, type, &block).tap do |doc|
    base.persisted? ? doc.save! : raise_unsaved(doc)
  end
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



114
115
116
117
118
119
120
121
# File 'lib/mongoid/relations/referenced/many.rb', line 114

def delete(document)
  target.delete(document) do |doc|
    if doc
      unbind_one(doc)
      cascade!(doc)
    end
  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(:conditions => { :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



137
138
139
# File 'lib/mongoid/relations/referenced/many.rb', line 137

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(:conditions => { :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



155
156
157
# File 'lib/mongoid/relations/referenced/many.rb', line 155

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:

Since:

  • 2.1.0



172
173
174
# File 'lib/mongoid/relations/referenced/many.rb', line 172

def each
  target.each { |doc| yield(doc) if block_given? }
end

#find(*args) ⇒ Document, Criteria

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 ])

Conditionally find all matching documents.

person.posts.find(:all, :conditions => { :title => "Sir" })

Conditionally find the first document.

person.posts.find(:first, :conditions => { :title => "Sir" })

Conditionally find the last document.

person.posts.find(:last, :conditions => { :title => "Sir" })

Parameters:

Returns:

Since:

  • 2.0.0.beta.1



201
202
203
# File 'lib/mongoid/relations/referenced/many.rb', line 201

def find(*args)
  criteria.find(*args)
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



230
231
232
233
234
235
# File 'lib/mongoid/relations/referenced/many.rb', line 230

def nullify
  criteria.update(.foreign_key => nil)
  target.clear do |doc|
    unbind_one(doc)
  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



247
248
249
250
251
252
253
254
255
256
257
# File 'lib/mongoid/relations/referenced/many.rb', line 247

def purge
  unless .destructive?
    nullify
  else
    criteria.delete_all
    target.clear do |doc|
      unbind_one(doc)
      doc.destroyed = true
    end
  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:

Returns:

  • (Many)

    The relation.

Since:

  • 2.0.0.rc.1



272
273
274
275
276
277
278
279
# File 'lib/mongoid/relations/referenced/many.rb', line 272

def substitute(replacement)
  tap do |proxy|
    if replacement != proxy.in_memory
      proxy.purge
      proxy.push(replacement.compact) if replacement
    end
  end
end