ActiveRecord: validate_uniqueness_of is case sensitive by default

Posted About 10 years ago. Visible to the public. Repeats.

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
Last edit
3 months ago
Niklas Hasselmeyer
Keywords
entry
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2014-03-20 12:40)