Ruby

Ruby

Made by DeepSource

uniqueness: true used on a field that is not an index RB-W1022

Bug risk
Major

Defining uniqueness: true on an ActiveRecord model can be error prone if the column hasn't been declared unique at the database level.

This is error prone due to 2 reasons:

  1. It is possible for 2 different database connections to determine that the field is unique and commit to the DB. This will create 2 entries as uniqueness is not checked for at the DB level.

  2. The validation executes a SELECT statement with the target column when inserting/updating a record. If the column does not have an index and the table is large, the query will be heavy.

Bad practice

# If the schema does not have a unique index
validates :account, uniqueness: true

Recommended

# If the schema has a unique index
validates :account, uniqueness: true

# If the schema does not have a unique index
validates :account, length: { minimum: MIN_LENGTH }