summaryrefslogtreecommitdiff
path: root/lib/gitlab/import/errors.rb
blob: b9e8c9135fd4b706186a37bf7464d7dd9190b488 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

module Gitlab
  module Import
    module Errors
      # Merges all nested subrelation errors into base errors object.
      #
      # @example
      #   issue = Project.last.issues.new(
      #     title: 'test',
      #     author: User.first,
      #     notes: [Note.new(
      #               award_emoji: [AwardEmoji.new(name: 'test')]
      #            )])
      #
      #   issue.validate
      #   issue.errors.full_messages
      #   => ["Notes is invalid"]
      #
      #   Gitlab::Import::Errors.merge_nested_errors(issue)
      #   issue.errors.full_messages
      #   => ["Notes is invalid",
      #       "Award emoji is invalid",
      #       "Awardable can't be blank",
      #       "Name is not a valid emoji name",
      #       ...
      #      ]
      def self.merge_nested_errors(object)
        object.errors.each do |error|
          association = object.class.reflect_on_association(error.attribute)

          next unless association&.collection?

          records = object.public_send(error.attribute).select(&:invalid?) # rubocop: disable GitlabSecurity/PublicSend

          records.each do |record|
            merge_nested_errors(record)

            object.errors.merge!(record.errors)
          end
        end
      end
    end
  end
end