Firstly, can anyone explain how unique index works in databases?
Suppose I have a User model with a name column
and I add a unique index
on it
Db Unique index and i quote from this SO question is:
Unique Index in a database is an index on that column that also enforces the constraint that you cannot have two equal values in that column in two different rows
While ROR uniqueness validation should do the same but from application level, meaning that the following scenario could rarely but easily happen:
Which happened to me a month ago and got advise to solve it using DB unique index in this SO question
By the way this workaround is well documented in Rails:
The best way to work around this problem is to add a unique index to the database table using ActiveRecord::ConnectionAdapters::SchemaStatements#add_index. In the rare case that a race condition occurs, the database will guarantee the field’s uniqueness