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

Attempted to save before the parent .

Error message

Attempted to save %{document} before the parent %{base}.

What it means

raise_unsaved fires when create/create! is called on an association whose parent base document has not been persisted yet. The child would be written with no reference to a stored parent, so Mongoid refuses.

Solutions

  1. Save the parent document before calling create on its association
  2. Build instead of create (e.g. association.build) and save the parent afterwards
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at lib/mongoid/association/proxy.rb:165 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/7af3786e0dc9b54c. Report an issue: GitHub.

Appendix: source

Thrown at lib/mongoid/association/proxy.rb:165

      # @example Raise the error.
      #   relation.raise_mixed
      #
      # @raise [ Errors::MixedRelations ] The error.
      def raise_mixed
        raise Errors::MixedRelations.new(_base.class, _association.klass)
      end

      # When the base is not yet saved and the user calls create or create!
      # on the association, this error will get raised.
      #
      # @example Raise the error.
      #   relation.raise_unsaved(post)
      #
      # @param [ Document ] doc The child document getting created.
      #
      # @raise [ Errors::UnsavedDocument ] The error.
      def raise_unsaved(doc)
        raise Errors::UnsavedDocument.new(_base, doc)
      end

      # Executes a callback method
      #
      # @example execute the before add callback
      #   execute_callback(:before_add)
      #
      # @param [ Symbol ] callback to be executed
      def execute_callback(callback, doc)
        _association.get_callbacks(callback).each do |c|
          if c.is_a? Proc
            c.call(_base, doc)
          else
            _base.send c, doc
          end
        end
      end

View on GitHub (pinned to 0da0e23d71)