Class: NestedAttributesUniquenessValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- NestedAttributesUniquenessValidator
- Defined in:
- lib/nested_attributes_uniqueness_validator.rb
Defined Under Namespace
Classes: MissingScopeError
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/nested_attributes_uniqueness_validator.rb', line 4 def validate_each(record, attribute, value) = (record) scope = [[:scope]].flatten.compact raise MissingScopeError if scope.empty? unless [:allow_destroyed] == true value = value.reject(&:marked_for_destruction?) end same_object = value.detect do |object| value.select do |obj| scope.map do |scope_attribute| a = obj.send(scope_attribute) b = object.send(scope_attribute) if [:allow_blank] == true (a == b) else (a.present? || b.present?) && (a == b) end end.all? end.count > 1 end return unless same_object.present? same_object.errors.add( [:attribute].presence || scope.first, [:message].presence || :taken ) record.errors.add(attribute, [:message].presence || :invalid) end |