ActiveRecord: validate_uniqueness_of is case sensitive by default

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.

(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.

Tobias Kraze over 8 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more