class Mongoid::Relations::Referenced::One

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

Public Class Methods

new(base, target, metadata) click to toggle source

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

@example Create the new relation.

Referenced::One.new(base, target, metadata)

@param [ Document ] base The document this relation hangs off of. @param [ Document ] target The target (child) of the relation. @param [ Metadata ] metadata The relation's metadata.

# File lib/mongoid/relations/referenced/one.rb, line 18
def initialize(base, target, metadata)
  init(base, target, metadata) do
    raise_mixed if klass.embedded? && !klass.cyclic?
    characterize_one(target)
    bind_one
    target.save if persistable?
  end
end

Public Instance Methods

nullify() click to toggle source

Removes the association between the base document and the target document by deleting the foreign key and the reference, orphaning the target document in the process.

@example Nullify the relation.

person.game.nullify

@since 2.0.0.rc.1

# File lib/mongoid/relations/referenced/one.rb, line 35
def nullify
  unbind_one
  target.save
end
substitute(replacement) click to toggle source

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

@example Replace the relation.

person.game.substitute(new_game)

@param [ Array<Document> ] replacement The replacement target.

@return [ One ] The relation.

@since 2.0.0.rc.1

# File lib/mongoid/relations/referenced/one.rb, line 52
def substitute(replacement)
  unbind_one
  if persistable?
    if metadata.destructive?
      send(metadata.dependent)
    else
      save if persisted?
    end
  end
  One.new(base, replacement, metadata) if replacement
end