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

Don't set foreign key on associated object if the parent is not persisted

    XMLWordPrintable

Details

    Description

      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.

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              dragosm Dragos Miron
              Votes:
              0 Vote for this issue
              Watchers:
              6 Start watching this issue

              Dates

                Created:
                Updated: