mongodb/mongoid · error · Mongoid::Errors::DeleteRestriction

Cannot destroy because of dependent ' '.

Error message

Cannot destroy %{document} because of dependent '%{relation}'.

What it means

Raised by _dependent_restrict_with_exception! when destroying a document with dependent: :restrict_with_exception while the named association still holds related documents. Destruction is aborted and the parent is left intact.

Solutions

  1. Destroy or detach the associated documents before destroying the parent
  2. Use dependent: :restrict_with_error to add a validation error instead of raising
  3. Rescue Mongoid::Errors::DeleteRestriction where the condition is expected
Defensive patterns

Strategy: try-catch

When it happens

Trigger: Thrown at lib/mongoid/association/depending.rb:127 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of mongodb/mongoid@0da0e23d71 (2026-08-23). Data as JSON: /api/errors/92215edb43b6c47d. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/association/depending.rb:127

        return unless relation = without_autobuild { send(association.name) }

        if relation.is_a?(Enumerable)
          relation.entries
          relation.each { |doc| doc.destroy }
        else
          relation.destroy
        end
      end

      def _dependent_nullify!(association)
        return unless relation = without_autobuild { send(association.name) }

        relation.nullify
      end

      def _dependent_restrict_with_exception!(association)
        if (relation = without_autobuild { send(association.name) }) && !relation.blank?
          raise Errors::DeleteRestriction.new(relation, association.name)
        end
      end

      def _dependent_restrict_with_error!(association)
        return unless (relation = without_autobuild { send(association.name) }) && !relation.blank?

        errors.add(association.name, :destroy_restrict_with_error_dependencies_exist)
        throw(:abort, false)
      end
    end
  end
end

View on GitHub (pinned to 0da0e23d71)