Hi there,
I am beginning Phoenix/Ecto (coming from Rails as many) and I found myself puzzled by how to handler columns with a NOT NULL
constraint.
I have a basic User
Schema as follows:
schema "users" do
field :email, :string
field :first_name, :string
field :last_name, :string
end
And NOT NULL constraint on all fields (among other things). I would like to handle this through Ecto, so I added two Ecto.Changeset
s: one on for creation and one for update as follows:
def changeset(user, attrs) do
user
|> cast(attrs, [:first_name, :last_name, :email])
end
def creation_changeset(user, attrs) do
user
|> changeset(attrs)
|> validate_required(attrs, [:first_name, :last_name, :email])
end
The creation_changeset\2
method works as expected: it does not allow creation without all fields, and any “blank” value is reported correctly.
The Changeset\2
method does not work correclty, if I do something like:
some_user
|> User.changeset(%{email: nil, first_name: nil, last_name: nil})
I get a valid Ecto.Changeset
with changes: %{email: nil, first_name: nil, last_name: nil}
and when sent to the database (via Repo.update\1
) it raises a Postgrex.Error
instead a returning an erroneous Changeset…
Does anybody know how to get this right ?
It feels super basic but I could not understand how to do it
Regards