Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-4160

Don't persist document if associated document is invalid with optional: false

    • Minor Change

      After discussion we have decided to leave the below problem the way it is because it is consistent with rails. We have decided to make it such that, when optional is false (or unset with the global belongs_to_required_by_default flag set to true), and the associated document is invalid, neither the document nor the associated document is persisted. See this PR https://github.com/mongodb/mongoid/pull/5303 for more details

      Original ticket:

      class Parent
        has_one :child
        field :name
        validate :name, presence: :true
      end
      
      class Child
        belongs_to :parent
      end
      
      child = Child.new
      child.parent = Parent.new #so invalid, no name
      child.save
      

      In this instance child will save without performing the validations on parent.
      It sounds legit because child is a "child" and parent is a "parent", so the inverse save should be done.
      In this case, if parent would be valid, they would both save
      But because parent is invalid, only child saves.
      Using validates_associated works, as you would expect.

      THE PROBLEM
      =======
      Child has been saved with reference in parent_id to an object that doesn't exist.
      We see this as a bug, I would expect that at least parent_id to be nil.

      Transactional databases don't save anything because everything is wrapped in a transaction and because Parent cannot save everything is reverted.
      In mongoid, because a reference is given to the object on initialization, that reference is going to child object.

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            dragos.miron@simplybusiness.co.uk Dragos Miron
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: