activerecord’s validates_uniqueness_of validates nil values

the default behavior of activerecord’s validates_uniqueness_of includes validating nil values. so, that means that only one row in your table can have a value of nil for the column on which you’re validating uniqueness.

validates_uniqueness_of login_token # triggers for nil. bad!

fortunately, those guys that make the rails go, they’re smart. you can change this default behavior and all will work well. simply set the allow_nil option to true

validates_uniqueness_of login_token,
   :allow_nil => true # doesn’t trigger for nil. good!

this is all in the activerecord doc, but it’s hard to find.

DEFAULT_VALIDATION_OPTIONS = { :on => :save, :allow_nil => false, :message => nil }

go forth and validate.


About this entry