Ecto.Changeset.assoc_constraint
You're seeing just the function
assoc_constraint
, go back to Ecto.Changeset module for more information.
Specs
Checks the associated field exists.
This is similar to foreign_key_constraint/3
except that the
field is inferred from the association definition. This is useful
to guarantee that a child will only be created if the parent exists
in the database too. Therefore, it only applies to belongs_to
associations.
As the name says, a constraint is required in the database for this function to work. Such constraint is often added as a reference to the child table:
create table(:comments) do
add :post_id, references(:posts)
end
Now, when inserting a comment, it is possible to forbid any comment to be added if the associated post does not exist:
comment
|> Ecto.Changeset.cast(params, [:post_id])
|> Ecto.Changeset.assoc_constraint(:post)
|> Repo.insert
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 + association field. May be required explicitly for complex cases