module Sequel::Plugins::ValidateAssociated::InstanceMethods

Private Instance Methods

delay_validate_associated_object(reflection, obj) click to toggle source

Delay validating the associated object until validating the current object.

# File lib/sequel/plugins/validate_associated.rb, line 46
def delay_validate_associated_object(reflection, obj)
  after_validation_hook{validate_associated_object(reflection, obj)}
end
validate_associated_object(reflection, obj) click to toggle source

Validate the given associated object, adding any validation error messages from the given object to the parent object.

# File lib/sequel/plugins/validate_associated.rb, line 52
def validate_associated_object(reflection, obj)
  return if reflection[:validate] == false
  association = reflection[:name]
  if (reflection[:type] == :one_to_many || reflection[:type] == :one_to_one) && (key = reflection[:key]).is_a?(Symbol) && !(pk_val = obj.values[key])
    p_key = pk unless pk.is_a?(Array)
    if p_key
      obj.values[key] = p_key
    else
      ignore_key_errors = true
    end
  end

  unless obj.valid?
    if ignore_key_errors
      # Ignore errors on the key column in the associated object. This column
      # will be set when saving to a presumably valid value using a column
      # in the current object (which may not be available until after the current
      # object is saved).
      obj.errors.delete(key)
      obj.errors.delete_if{|k,| Array === k && k.include?(key)}
    end

    obj.errors.full_messages.each do |m|
      errors.add(association, m)
    end
  end

  nil
end