Ecto’s constraints are a great example of that. Like Rails, Ecto has validations. But unlike Rails, Ecto also has constraints. Validating uniqueness

Ecto's uniqueness constraint vs Rails' uniqueness validation

submited by
Style Pass
2022-05-21 19:30:04

Ecto’s constraints are a great example of that. Like Rails, Ecto has validations. But unlike Rails, Ecto also has constraints. Validating uniqueness is the example that most easily comes to my mind.

With Rails, we can validate uniqueness through the validate method (with a uniqueness option) or through the validates_uniqueness_of method. Both do the same:

It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique.

Because the validation happens before records are inserted into the database, we always have the possibility of a race condition — for example, if one user quickly submits the same form twice or two users submit the form at the same time.

You can either choose to let this error propagate (which will result in the default Rails exception page being shown), or you can catch it and restart the transaction

Leave a Comment