Ecto.Changeset.check_constraint
check_constraint
, go back to Ecto.Changeset module for more information.
Checks for a check constraint in the given field.
The check constraint works by relying on the database to check if the check constraint has been violated or not and, if so, Ecto converts it into a changeset error.
In order to use the check constraint, the first step is to define the check constraint in a migration:
create constraint("users", :price_must_be_positive, check: "price > 0")
Now that a constraint exists, when modifying users, we could annotate the changeset with a check constraint so Ecto knows how to convert it into an error message:
cast(user, params, [:price])
|> check_constraint(:price, name: :price_must_be_positive)
Now, when invoking Repo.insert/2
or Repo.update/2
, if the
price is not positive, it will be converted into an error and
{:error, changeset}
returned by the repository. Note that the error
will occur only after hitting the database so it will not be visible
until all other validations pass.
Options
:message
- the message in case the constraint check fails. Defaults to "is invalid":name
- the name of the constraint. Required.:match
- how the changeset constraint name is matched against the repo constraint, may be:exact
,:suffix
or:prefix
. Defaults to:exact
.:suffix
matches any repo constraint whichends_with?
:name
to this changeset constraint.:prefix
matches any repo constraint whichstarts_with?
:name
to this changeset constraint.