The problem is that Rails implements model-based uniqueness restrictions. Basically, they work by querying the database if there are any existing rows with the attribute and refuse to create the object, if so.
However, given the frequently used transaction isolation levels (usually repeated by default), you may have overlapping transactions that successfully check the constraint and then insert their objects without knowing each other.
This is because, to achieve real uniqueness, you have to define a constraint in the database using UNIQUE indexes. This is much more important than defining constraints in your model, since only the database is able to provide real uniqueness by checking the constraint, since the row is actually filled / updated during the operation with several / threads.
The only reason you still want to further define the restriction in Ruby is that its error messages are much more friendly, and therefore you can handle the usual case. If the database restriction is removed, you just get a false value to save without much information about what went wrong (but you will still have a consistent database)
source share