如何在Ecto中将关联传递给变更集?

时间:2016-06-16 06:26:33

标签: elixir phoenix-framework ecto

我有一个非常简单的Comment模型:

  schema "comments" do
    field :content, :string
    belongs_to :user, MyApp.User
    timestamps
  end

我想创建一条新记录,我希望changeset验证该用户是否存在。我怎么能这样做?

我的ecto版本为1.1.8

1 个答案:

答案 0 :(得分:4)

执行此操作的正确方法是让数据库处理数据完整性。在您的应用程序中为此写一张支票很容易出现竞争条件。如果在您的验证和User插入之间删除Comment该怎么办?如果已删除任何现有User的{​​{1}},该怎么办?在数据库中处理此问题将确保您的数据库中永远不会有无效数据。

首先,确保Comment字段设置为user_id

references(:users)

然后,在create table(:comments) do ... # Check out the various :on_delete options you can pass to here: https://hexdocs.pm/ecto/Ecto.Migration.html#references/2 add :user_id, references(:users, on_delete: :nilify_all) end 函数中,在汇总到changeset之后,添加以下内容:

cast

这会将与数据库返回的|> Ecto.Changeset.assoc_constraint(:user) 相关的错误转换为正常的Changeset错误。您可以阅读有关user_id here的更多信息。另请参阅Ecto.Changeset.html#foreign_key_constraint/3