尝试删除结构时出现 Ecto 约束错误

Ecto constraint error when attempting to delete struct

我有一个 User 模型 has_many 医疗信息和医疗信息 belongs_to 用户。

当我尝试删除具有关联记录(医疗信息)的 User 时,Ecto 出现以下错误:

 ** (Ecto.ConstraintError) constraint error when attempting to delete struct:

     * foreign_key: medical_informations_user_id_fkey

 If you would like to convert this constraint into an error, please
 call foreign_key_constraint/3 in your changeset and define the proper
 constraint name. The changeset has not defined any constraint.

我尝试将 foreign_key_constraint/3 添加到我在两个模型中的默认变更集,但错误仍然存​​在。

Ecto 有一个约束来检查如果没有关联的记录是否可以删除条目 Ecto.Changeset.no_assoc_constraint/3。通过此验证,我得到一个很好的错误,我可以像这样使用 associated_records are still associated to this entry.

另一个有用的约束是 Ecto.Changeset.foreign_key_constraint/3,它有助于保证仅当父项也存在于数据库中时才会创建子项。