Rails what's difference in unique index and validates_uniqueness_of

前端 未结 3 2325
难免孤独
难免孤独 2021-02-15 02:43

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

3条回答
  •  独厮守ぢ
    2021-02-15 03:13

    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:

    • User A submits form
    • Rails checks database for existing ID for User A- none found
    • User B submits form
    • Rails checks database for existing ID for User B- none found
    • Rails Saves user A record
    • Rails saves user B record

    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

提交回复
热议问题