Method: Glue::Validation::ClassMethods#validate_unique
- Defined in:
- lib/og/validation.rb
#validate_unique(*params) ⇒ Object
Validates that the given field(s) contain unique values. Ensures that if a record is found with a matching value, that it is the same record, allowing updates.
The Og libraries are required for this method to work. You can override this method if you want to use another OR mapping library.
Example
validate_unique :param, :msg => ‘Value is already in use’ – TODO: :unique should implicitly generate validate_unique. ++
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/og/validation.rb', line 35 def validate_unique *params c = parse_config(params, :on => :save) params.each do |field| c[:msg] ||= "#{self.name} with this #{field} already exists" define_validation(:unique, field, c[:on]) do |obj| # What to do if value is nil? Right now it is an empty string, # which can need to be unique. value = obj.send(field) || '' others = [*obj.class.send("find_by_#{field}".to_sym, value)] unless others[0].nil? obj.errors.add(field, c[:msg]) if others.size > 1 or others[0].oid != obj.oid end end end end |