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

Copy
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

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

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Avatar
Tobias Kraze
Last edit:
about 20 hours ago
by Michael Leimstädtner
Keywords:
entry
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