Ecto.Changeset.foreign_key_constraint
foreign_key_constraint
, go back to Ecto.Changeset module for more information.
Specs
Checks for foreign key constraint in the given field.
The foreign key constraint works by relying on the database to check if the associated data exists or not. This is useful to guarantee that a child will only be created if the parent exists in the database too.
In order to use the foreign key constraint the first step is to define the foreign key in a migration. This is often done with references. For example, imagine you are creating a comments table that belongs to posts. One would have:
create table(:comments) do
add :post_id, references(:posts)
end
By default, Ecto will generate a foreign key constraint with name "comments_post_id_fkey" (the name is configurable).
Now that a constraint exists, when creating comments, we could annotate the changeset with foreign key constraint so Ecto knows how to convert it into an error message:
cast(comment, params, [:post_id])
|> foreign_key_constraint(:post_id)
Now, when invoking Repo.insert/2
or Repo.update/2
, if the
associated post does not exist, it will be converted into an
error and {:error, changeset}
returned by the repository.
Options
:message
- the message in case the constraint check fails, defaults to "does not exist":name
- the constraint name. By default, the constraint name is inferred from the table + field. May be required explicitly for complex cases