@@ -645,10 +645,16 @@ defmodule Ecto.Schema do
645
645
## Options
646
646
647
647
* `:default` - Sets the default value on the schema and the struct.
648
+
648
649
The default value is calculated at compilation time, so don't use
649
650
expressions like `DateTime.utc_now` or `Ecto.UUID.generate` as
650
651
they would then be the same for all records: in this scenario you can use
651
- the `:autogenerate` option to generate at insertion time.
652
+ the `:autogenerate` option to generate at insertion time.
653
+
654
+ The default value is validated against the field's type at compilation time
655
+ and it will raise an ArgumentError if there is a type mismatch. If you cannot
656
+ infer the field's type at compilation time, you can use the
657
+ `:skip_default_validation` option on the field to skip validations.
652
658
653
659
Once a default value is set, if you send changes to the changeset that
654
660
contains the same value defined as default, validations will not be performed
@@ -685,6 +691,9 @@ defmodule Ecto.Schema do
685
691
when inspected in changes inside a `Ecto.Changeset` and be excluded
686
692
from inspect on the schema. Defaults to `false`.
687
693
694
+ * `:skip_default_validation` - When true, it will skip the type validation
695
+ step at compile time.
696
+
688
697
"""
689
698
defmacro field ( name , type \\ :string , opts \\ [ ] ) do
690
699
quote do
@@ -1881,7 +1890,7 @@ defmodule Ecto.Schema do
1881
1890
1882
1891
type = check_field_type! ( mod , name , type , opts )
1883
1892
Module . put_attribute ( mod , :changeset_fields , { name , type } )
1884
- validate_default! ( type , opts [ :default ] )
1893
+ validate_default! ( type , opts [ :default ] , opts [ :skip_default_validation ] )
1885
1894
define_field ( mod , name , type , opts )
1886
1895
end
1887
1896
@@ -2141,7 +2150,8 @@ defmodule Ecto.Schema do
2141
2150
Module . put_attribute ( mod , :struct_fields , { name , assoc } )
2142
2151
end
2143
2152
2144
- defp validate_default! ( type , value ) do
2153
+ defp validate_default! ( _type , _value , true ) , do: :ok
2154
+ defp validate_default! ( type , value , _skip ) do
2145
2155
case Ecto.Type . dump ( type , value ) do
2146
2156
{ :ok , _ } ->
2147
2157
:ok
0 commit comments