Class: Xeroizer::Record::Validator::AssociatedValidator

Inherits:
Xeroizer::Record::Validator show all
Defined in:
lib/xeroizer/record/validators/associated_validator.rb

Instance Attribute Summary

Attributes inherited from Xeroizer::Record::Validator

#attribute, #options

Instance Method Summary collapse

Methods inherited from Xeroizer::Record::Validator

#condition?, #initialize, #run_validator?, #validate

Constructor Details

This class inherits a constructor from Xeroizer::Record::Validator

Instance Method Details

#valid?(record) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/xeroizer/record/validators/associated_validator.rb', line 8

def valid?(record)
  case record.class.fields[attribute][:type]
    when :belongs_to
      return true if options[:allow_blanks] && record[attribute].nil?
      unless record[attribute].is_a?(Xeroizer::Record::Base) && record[attribute].valid?
        record.errors << [attribute, options[:message] || "must be valid"]
      end
      
    when :has_many
      return true if options[:allow_blanks] && (record[attribute].nil? || (record[attribute].is_a?(Array) && record[attribute].size == 0))
      if record[attribute].is_a?(Array) && record[attribute].size > 0
        unless record[attribute].all? { | r | r.is_a?(Xeroizer::Record::Base) && r.valid? }
          record.errors << [attribute, options[:message] || "must all be valid"]
        end
      else
        record.errors << [attribute, "must have one or more records"] 
      end
  end
end