Sha256: 2e3e261ff34ca1d202ec1e336ee9744f52c0bf17077c841c333f1ac6427c9ef1

Contents?: true

Size: 936 Bytes

Versions: 1

Compression:

Stored size: 936 Bytes

Contents

module PhModel
  module Concerns
    module AttributeNestedValidation
      extend ActiveSupport::Concern

      included do |other|
        other.validate :validate_nested_attributes
      end

      def validate_nested_attributes
        self.class.attributes.each do |attribute_name, info|
          value = send(attribute_name)
          if info[:type].is_a? Array
            if value.respond_to? :each_with_index
              value.each_with_index do |item_value, index|
                check_one(item_value, "#{attribute_name}[#{index}]")
              end
            end
          else
            check_one(value, attribute_name)
          end
        end
      end

      def check_one(value, attribute_name)
        return if !value.respond_to?(:valid?) || value.valid?
        value.errors.full_messages.each do |message|
          errors.add(:base, "#{attribute_name}.#{message}")
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ph_model-1.0.0 lib/ph_model/concerns/attribute_nested_validation.rb