Class: Mongoid::Validations::ReferencedValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- Mongoid::Validations::ReferencedValidator
- Defined in:
- lib/mongoid/validations/referenced.rb
Overview
Validates whether or not an association is valid or not. Will correctly handle has one and has many associations. Will not load associations if they aren’t already in memory.
Instance Method Summary collapse
-
#validate(document) ⇒ Object
Validate the document for the initialized attributes.
-
#validate_each(document, attribute, value) ⇒ Object
Validates that the already loaded associations provided are either all nil or unchanged or all valid.
Instance Method Details
#validate(document) ⇒ Object
Validate the document for the initialized attributes. Will not load any association that’s not currently loaded.
21 22 23 24 25 26 |
# File 'lib/mongoid/validations/referenced.rb', line 21 def validate(document) attributes.each do |attribute| value = document.instance_variable_get("@#{attribute}".to_sym) validate_each(document, attribute, value) end end |
#validate_each(document, attribute, value) ⇒ Object
Validates that the already loaded associations provided are either all nil or unchanged or all valid. If neither is true then the appropriate errors will be added to the parent document.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/mongoid/validations/referenced.rb', line 38 def validate_each(document, attribute, value) document.validated = true valid = if !value || !value.target true else Array.wrap(value).collect do |doc| if doc.nil? || (!doc.changed? && !doc.new_record?) true else doc.validated? ? true : doc.valid? end end.all? end document.validated = false return if valid document.errors.add(attribute, :invalid, .merge(:value => value)) end |