你想使用唯一约束/3 http://hexdocs.pm/ecto/Ecto.Changeset.html#unique_constraint/3。这与 Active Record 不同,因为它使用数据库来确保唯一性。 Active Record 将对具有相同值的记录进行查询,如果返回任何记录,则会失败。这有一个竞争条件,如果在获取以检查唯一性和插入记录之间插入一个值,您将最终得到重复数据或引发错误(取决于是否在数据库上设置了索引。unique_constraint/3
没有这个竞争条件。
值得注意的一件事是,由于在尝试插入之前不知道唯一性,因此唯一约束将在验证后发生。不可能同时显示验证错误和约束错误。
The database you are using must support unique constraints too. They won't work with SQLite. You can read more on the [GitHub issue]https://github.com/elixir-lang/ecto/issues/865 https://github.com/elixir-lang/ecto/issues/865).
使用 SQLite3 数据库时,您只需使用ecto3_sqlite3
适配器,并且唯一约束将按预期工作。
添加到您的mix.exs
:
{:ecto_sqlite3, "~> 0.7.7"},
在您的迁移中:
create unique_index(:users, [:email])
然后在你的模型中:
cast(user, params, ~w(email), ~w())
|> unique_constraint(:email)
值得注意的是,Ecto 曾经提供validate_unique/3
通过对数据库进行查询来工作的函数,但它已被弃用unique_constraint/3
In 版本0.16.0 https://github.com/elixir-lang/ecto/releases/tag/v0.16.0