-
Type:
Bug
-
Resolution: Unresolved
-
Priority:
Unknown
-
Affects Version/s: None
-
Component/s: None
-
None
-
None
-
Ruby Drivers
-
None
-
None
-
None
-
None
-
None
-
None
COPIED FROM https://github.com/mongodb/mongoid/discussions/5954
Hey everyone,
I encountered what I believe is an unexpected behavior in Mongoid when using default values for fields. I couldn't find any mention of this in the documentation, so I'm reporting it here to confirm whether this is the intended behavior. If it is, could you point me to where this happens in the code and explain the reasoning behind it?
Issue
When a field has a default value, Mongoid incorrectly flags it as changed (dirty), even if the value was not explicitly modified by the user.
Example Scenario
Consider the following model:
class DummyModelinclude Mongoid::Document# I've also tried using the default as: `default: -> { false }`field :foo, type: Mongoid::Boolean, default: falseend
Now, when instantiating a new object:
klass = DummyModel.newklass.persisted? # false (not yet saved)klass.foo_changed? # true (incorrectly flagged as changed)klass.foo_change # [nil, false] (transition from uninitialized to default value)klass.foo_was # nil (expected to be false)
Expected Behavior
Fields with default values should not be marked as changed unless explicitly modified by the user. foo_changed? should return false unless foo was explicitly set to a different value.
Current versions
- Mongoid: 7.5.4
- Ruby: 3.0.7
- Rails: 6.1.7.8