-
Type: Bug
-
Resolution: Done
-
Priority: Major - P3
-
Affects Version/s: 4.0.0 final
-
Component/s: Associations, Persistence, Validations
-
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.
- causes
-
MONGOID-5635 default value of belongs_to_required_by_default causes performance issues
- Closed
-
MONGOID-5704 Mongoid 8.x performance and validation issues with belongs_to associations
- Closed
- is duplicated by
-
MONGOID-4621 Validate belongs_to target when saving by default
- Closed
- is related to
-
MONGOID-3601 Don't mark embedded objects as persisted when the parent is invalid
- Closed