Reputation: 5629
In Ecto, you can give fields in your Schema a default value by specifying them like field :name, default: "john"
. In the docs, it is stated that this default is stored at compile-time, and that things like Date.now
or UUID.generate
do not work.
My question is: How do we create these variable defaults?
One could say 'just set the value after creating the struct'. However, when working with virtual fields, this is not possible. When you use e. g. Repo.all(MyModel)
or any other querying-commands, virtual fields are set to their default fixed value.
How can we create variable schema field defaults?
Upvotes: 2
Views: 3048
Reputation: 11278
It is not possible. Ecto simply defines a struct and Elixir structs are expanded at compile time.
You can get around this by explicitly having a function to produce the struct with default values or do this in the changeset function via put_change
and similar.
Upvotes: 4