Module: Mongoid::Association::Depending

Extended by:
ActiveSupport::Concern
Included in:
Mongoid::Association
Defined in:
build/mongoid-7.0/lib/mongoid/association/depending.rb

Overview

This module defines the behaviour for setting up cascading deletes and nullifies for relations, and how to delegate to the appropriate strategy.

Constant Summary collapse

STRATEGIES =

The valid dependent strategies.

Since:

  • 7.0

[
    :delete_all,
    :destroy,
    :nullify,
    :restrict_with_exception,
    :restrict_with_error
]
RESTRICT_ERROR_MSG =

The error message when a strategy cannot delete objects because there are associated objects.

Since:

  • 7.0

'Cannot delete record because associated objects exist.'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.define_dependency!(association) ⇒ Class

Attempt to add the cascading information for the document to know how to handle associated documents on a removal.

Examples:

Set up cascading information

Mongoid::Association::Depending.define_dependency!(association)

Parameters:

  • association (Association)

    The association metadata.

Returns:

  • (Class)

    The class of the document.

Since:

  • 2.0.0.rc.1



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'build/mongoid-7.0/lib/mongoid/association/depending.rb', line 57

def self.define_dependency!(association)
  validate!(association)
  association.inverse_class.tap do |klass|
    if klass.dependents_owner != klass
      klass.dependents = []
      klass.dependents_owner = klass
    end

    if association.dependent && !klass.dependents.include?(association)
      klass.dependents.push(association)
    end
  end
end

.validate!(association) ⇒ Object



71
72
73
74
75
76
77
# File 'build/mongoid-7.0/lib/mongoid/association/depending.rb', line 71

def self.validate!(association)
  unless STRATEGIES.include?(association.dependent)
    raise Errors::InvalidDependentStrategy.new(association,
                                               association.dependent,
                                               STRATEGIES)
  end
end

Instance Method Details

#apply_delete_dependencies!Object

Perform all cascading deletes, destroys, or nullifies. Will delegate to the appropriate strategy to perform the operation.

Examples:

Execute cascades.

document.apply_delete_dependencies!

Since:

  • 2.0.0.rc.1



86
87
88
89
90
91
92
# File 'build/mongoid-7.0/lib/mongoid/association/depending.rb', line 86

def apply_delete_dependencies!
  self.class._all_dependents.each do |association|
    if association.try(:dependent)
      send("_dependent_#{association.dependent}!", association)
    end
  end
end