giovedì 11 novembre 2010

Case insensitive uniqueness validation in rails 3

The default uniqueness validation (using sexy validations) in Rails 3 is case sensitive. This means that if you wrote the following class, with the following validation:
Class User < ActiveRecord::Base

  validates :username, :presence => true, :uniqueness => true

end
these usernames will pass the validation and will be stored in the database:
foo, Foo, fOo, fOO, ...
To avoid this problem you should make a change to the previous model in order to make the uniqueness validation case insensitive. To acheive this you have to pass an hash of parameters to the uniqueness validator. The new code may look like this:
Class User < ActiveRecord::Base

  validates :username, :presence => true, :uniqueness => {:case_sensitive => false}

end
Hope this helps :)

Nessun commento:

Posta un commento