defmoduleApp.Userdo######## We don't need this anymore#########use Ecto.Schema##schema "users" do# field :name, :string# field :age, :integer, default: 0# field :password, :string, redact: true# has_many :posts, Post#enduseSorcery.Schema,%{meta:%{},fields:%{name:%{t::string},age:%{t::integer,default:0},password:%{t::string,redact:true},# No need for a has_many. In Sorcery, it is always the child that references the parent.}}end
In the above example, notice how we explicitly declare the :optional? key in every field. If this is set to true, and if no value is provided while generating the struct, then the field will use the FieldType default. For most fields (:integers, :strings, etc) this is nil. For lists and maps, it's an empty list or map respectively.
For example an :integer field with optional?: true will only ever be an integer.
But an :integer field with optional?: false might be either an integer or nil.
Meta Map
Before getting into the meat of it, notice the empty map called :meta up there? We can use it to set some schema-wide configuration.
:meta
types
Default
Description
:optional?
boolean
true
Whether every field allows nil. Individual fields can override. Maps and lists default to false.
Fields by type
:boolean
types
Optional?
Default
Description
:default
boolean
true
nil
If no value is given, this will be used.
:optional?
boolean
true
nil
Whether field is allowed to be nil
:string
types
Optional?
Default
Description
:min
integer
true
0
field must have at least this many characters.
:max
integer
true
25
field must have no more than this many characters.
:default
string
true
nil
If no value is given, this will be used.
:optional?
boolean
true
true
Whether field is allowed to be nil
:integer
types
Optional?
Default
Description
:min
integer
true
-10_000
field be at least this big.
:max
integer
true
10_000
field be no more than this big.
:default
integer
true
nil
If no value is given, this will be used.
:optional?
boolean
true
true
Whether field is allowed to be nil
:float
types
Optional?
Default
Description
:min
float
true
-10_000.0
field be at least this big.
:max
float
true
10_000.0
field be no more than this big.
:default
integer
true
nil
If no value is given, this will be used.
:optional?
boolean
true
true
Whether field is allowed to be nil
:list
types
Optional?
Default
Description
:min
integer
true
0
list must have at least this many items
:max
integer
true
10
list must have at most this many items
:default
integer
true
nil
If no value is given (and optional?: true), then nil.
:optional?
boolean
true
false
Whether field is allowed to be nil
:map
types
Optional?
Default
Description
:default
integer
true
nil
If no value is given (and optional?: true), then nil.
:optional?
boolean
true
false
Whether field is allowed to be nil
We don't both generating content inside maps. Too much complexity, and too far from the core goals of Sorcery.
:fk
This is still under construction. For now I would suggest using :integer instead.