@@ -827,6 +827,42 @@ Mongoid also defines the ``id`` field aliased to ``_id``. The ``id``
827
827
alias can :ref:`be removed <unalias-id>` if desired (such as to integrate
828
828
with systems that use the ``id`` field to store value different from ``_id``.
829
829
830
+ .. _uncastable-values:
831
+
832
+ Assigning Uncastable Values
833
+ ---------------------------
834
+
835
+ In Mongoid 8, Mongoid has standardized the treatment of the assignment of
836
+ "uncastable" values. A value is considered "uncastable" when it cannot be
837
+ coerced to the type of the field. For example:
838
+
839
+ .. code::
840
+
841
+ class User
842
+ include Mongoid::Document
843
+
844
+ field :name, type: Integer
845
+ end
846
+
847
+ User.new(name: [ "hello" ])
848
+
849
+ Assigning an array to a field of type Integer doesn't work since an array can't
850
+ be coerced to an Integer. The assignment of uncastable values to a field will
851
+ cause a ``nil`` to be written:
852
+
853
+ .. code::
854
+
855
+ user = User.new(name: [ "hello" ])
856
+ # => #<User _id: 62b222d43282a47bf73e3264, name: nil>
857
+
858
+ Note that the original uncastable values will be stored in the
859
+ ``attributes_before_type_cast`` hash with their field names:
860
+
861
+ .. code::
862
+
863
+ user.attributes_before_type_cast["name"]
864
+ # => ["hello"]
865
+
830
866
831
867
.. _customizing-field-behavior:
832
868
@@ -978,6 +1014,12 @@ setter methods for fields of your custom type.
978
1014
venue = Venue.new(location: point) # This uses the Point#mongoize instance method.
979
1015
venue = Venue.new(location: [ 12, 24 ]) # This uses the Point.mongoize class method.
980
1016
1017
+ .. note::
1018
+
1019
+ The ``mongoize`` method should return ``nil`` on values that are uncastable to
1020
+ your custom type. See the section on :ref:`Uncastable Values <uncastable-values>`
1021
+ for more details.
1022
+
981
1023
The class method ``demongoize`` does the inverse of ``mongoize``. It takes the raw object
982
1024
from the MongoDB Ruby driver and converts it to an instance of your custom type.
983
1025
In this case, the database driver returns an ``Array`` and we instantiate a ``Point`` from it.
0 commit comments