Uniqueness validation and rails

I found a strange behavior in uniqueness validation in rails and I wanted to keep it as a note. Let's say that we have a model category that it has a name attribute. We want the name attribute to be unique, so we add the following line:
validates :name, uniqueness: true
inside the category model. What will happen if we have a category with name "Cars" and we try to add a new one with the name "cars" (the only difference is the capitalization)?
BOOM! The new category will be saved and we will have two categories, one named "Cars" and one named "cars". The default behavior or uniqueness validation is to be case sensitive which means it will accept the same name but with a different capitalization. To avoid this behavior you should do something like:
validates :name, uniqueness: { case_sensitive: false }
This is one of the rarest times where rails doesn't behave as I expected. I am used to mysql case_insensitive style (do you remember when you are specifying in mysql, the collation and it has something like utf8_ci or latin_swedish_ci? The ci means case_insensitive) so I thought that the default would be not to accept the above. Keep that in mind next time.

comments powered by Disqus