I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Consider the following schema:
schema "addresses" do
field :name, :string, size: 100
field :company, :string, size: 100
field :street1, :string, size: 250
field :street2, :string, size: 250
field :city, :string, size: 100
field :state, :string, size: 2
field :zip, :string, size: 32
field :zip4, :string, size: 4 # NOT NULL?
This is correct but it is possible to enforce this constraint in your changeset function, which will yield a nice Changeset error rather than an exception.You can use validate_required in your changeset function. I’d still set null: false in the migration.
So far as I know, the “right” way to setup the changeset to make a field be required is to use the Changeset function validate_required. That is how we do it. If I take the validate_required function out of my Changeset and leave the field blank, I end up with a Postgrex exception along the lines:
** (exit) an exception was raised:
** (Postgrex.Error) ERROR 23502 (not_null_violation): null value in column "title" violates not-null constraint