在ecto中使字段唯一 [英] Making a field unique in ecto

查看:79
本文介绍了在ecto中使字段唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在ecto中使字段唯一



我认为这与其中的活动记录相同Ruby,但似乎不是

解决方案

您要使用unique_constraint/3 。这与Active Record不同,因为它使用数据库来确保唯一性。 Active Record将查询具有相同值的记录,如果返回任何记录,则它将失败。这有一个竞争条件,如果在获取数据以检查唯一性和插入记录之间插入一个值,则最终将导致重复数据或引发错误(取决于是否在数据库上设置了索引)。 code> unique_constraint / 3 没有这种竞争条件。



值得注意的是,由于唯一性直到尝试插入,唯一的约束将在验证后发生。无法同时显示验证和约束错误。



您使用的数据库必须支持唯一的约束也是如此。它们不适用于SQLite。您可以在 GitHub问题上阅读更多内容。 / p>

在您的迁移中:

 创建unique_index(:users,[:电子邮件])

然后在您的模型中:

  cast(用户,参数,〜w(电子邮件),〜w())
|> ; unique_constraint(:email)






值得注意的是ecto过去提供了 validate_unique / 3 函数,该函数通过对数据库进行查询而起作用,但是不推荐使用 unique_constraint / 3 版本0.16.0


How to make a field unique in ecto?

I thought it's the same as the active record in Ruby, but it seems it isn't

解决方案

You want to use unique_constraint/3. This is not like Active Record because it is using the database to ensure uniqueness. Active Record would do a query for records with the same value and if any were returned then it would fail. This has a race condition where, if a value is inserted between fetching to check uniqueness and inserting your record, you will either end up with duplicate data or an error being raised (depending on if an index is set on the database or not. unique_constraint/3 does not have this race condition.

One thing worth noting is that since the uniqueness is not known until an insert is attempted, the unique constraint will happen after your validations. It is not possible to display both validation and constraint errors at once.

The database you are using must support unique constraints too. They won't work with SQLite. You can read more on the GitHub issue.

In your migration:

create unique_index(:users, [:email])

Then in your model:

cast(user, params, ~w(email), ~w())
|> unique_constraint(:email)


It is worth noting that Ecto used to provide a validate_unique/3 function which worked by doing a query on the database, however it was deprecated in favour of unique_constraint/3 In version 0.16.0

这篇关于在ecto中使字段唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆