Posted over 8 years ago. Visible to the public. Repeats.

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.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Tobias Kraze
Last edit:
11 months ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more