Read more

ActiveRecord: validate_uniqueness_of is case sensitive by default

Tobias Kraze
March 20, 2014Software engineer at makandra GmbH

By default, Rails' validates_uniqueness_of does not consider "username" and "USERNAME" to be a collision. If you use MySQL this will lead to issues, since string comparisons are case-insensitive in MySQL.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

(If you use PostgreSQL, read this instead.)

Say you have a user model

class User < ActiveRecord::Base
  validates_uniqueness_of :name
end

with a unique index in the database.

If you try to create the users "user" and "USER", this will not trigger a validation error, but may fail with an SQL error due to duplicate index key.

You can change Rails' behaviour, by saying

class User < ActiveRecord::Base
  validates_uniqueness_of :name, case_sensitive: false
end

When you get an ActiveRecord::RecordNotUnique error (probably in combination with Mysql2::Error: Duplicate entry) for a string field, case sensitivity may be your issue.

Posted by Tobias Kraze to makandra dev (2014-03-20 13:40)