Module: Mongoid::EmbeddedErrors

Defined in:
lib/mongoid/embedded_errors/version.rb,
lib/mongoid/embedded_errors.rb

Constant Summary collapse

VERSION =
'2.1.1'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



6
7
8
9
10
11
# File 'lib/mongoid/embedded_errors.rb', line 6

def self.included(klass)
  # make sure that the alias only happens once:
  unless klass.instance_methods.include?(:errors_without_embedded_errors)
    klass.alias_method_chain(:errors, :embedded_errors)
  end
end

Instance Method Details

#errors_with_embedded_errorsObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mongoid/embedded_errors.rb', line 13

def errors_with_embedded_errors
  errors_without_embedded_errors.tap do |errs|
    embedded_relations.each do |name, |
      # name is something like pages or sections
      # if there is an 'is invalid' message for the relation then let's work it:
      next unless Array(public_send(name)).any? { |doc| doc.errors.any? }
      # first delete the unless 'is invalid' error for the relation
      errs[name].delete 'is invalid'
      errs.delete name.to_sym if errs[name].empty?
      # next, loop through each of the relations (pages, sections, etc...)
      [send(name)].flatten.reject(&:nil?).each_with_index do |rel, i|
        # get each of their individual message and add them to the parent's errors:
        next unless rel.errors.any?
        rel.errors.messages.each do |k, v|
          key = (.relation == Mongoid::Relations::Embedded::Many ? "#{name}[#{i}].#{k}" : "#{name}.#{k}").to_sym
          errs.delete(key)
          errs[key] = v
          errs[key].flatten!
        end
      end
    end
  end
end