Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation to ensure uniqueness of but ignoring empty values?

I have the following model field validation:

validates_uniqueness_of :acronym, :scope => [:group_id], :case_sensitive => false 

The problem is that this field is optional, and a empty/nil value is returning as being an acronym already taken. I only want to validate that an acronym is unique if a value was provided.. Is there a way to update this validation to only take place if there is an actual value.. not nil/empty?

Thanks

like image 213
AnApprentice Avatar asked Apr 15 '12 23:04

AnApprentice


1 Answers

Yes, there are two possible options that you can pass to validations for optional fields: :allow_blank or :allow_nil, which will skip the validations on blank and nil fields, respectively. If you change your validation to the following, you should get the behaviour you want:

validates_uniqueness_of :acronym, :allow_blank => true, :scope => [:group_id], :case_sensitive => false 
like image 185
tsherif Avatar answered Sep 29 '22 09:09

tsherif