Skip to content
This repository was archived by the owner on Sep 22, 2025. It is now read-only.

Commit 845910b

Browse files
authored
Add support for error details when adding attribute error (mirego#69)
1 parent b7e4f1c commit 845910b

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

lib/active_record/json_validator/validator.rb

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,10 @@ def validate_each(record, attribute, value)
2525
return if errors.empty? && record.send(:"#{attribute}_invalid_json").blank?
2626

2727
# Add error message to the attribute
28+
details = errors.map { |e| JSONSchemer::Errors.pretty(e) }
2829
message(errors).each do |error|
29-
error = error.is_a?(Hash) ? JSONSchemer::Errors.pretty(error) : error
30-
record.errors.add(attribute, error, value: value)
30+
error = JSONSchemer::Errors.pretty(error) if error.is_a?(Hash)
31+
record.errors.add(attribute, error, errors: details, value: value)
3132
end
3233
end
3334

@@ -68,10 +69,7 @@ def schema(record, schema = nil)
6869

6970
def message(errors)
7071
message = options.fetch(:message)
71-
72-
case message
73-
when Proc then [message.call(errors)].flatten if message.is_a?(Proc)
74-
else [message]
75-
end
72+
message = message.call(errors) if message.is_a?(Proc)
73+
[message].flatten
7674
end
7775
end

spec/json_validator_spec.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ def smart_data
4848
specify do
4949
expect(user).not_to be_valid
5050
expect(user.errors.full_messages).to eql(['Data root is missing required keys: country', 'Other data missing_keys country'])
51+
expect(user.errors.group_by_attribute[:data].first).to have_attributes(
52+
options: include(errors: ['root is missing required keys: country'])
53+
)
54+
expect(user.errors.group_by_attribute[:other_data].first).to have_attributes(
55+
options: include(errors: ['root is missing required keys: country'])
56+
)
5157
expect(user.data).to eql({ 'city' => 'Quebec City' })
5258
expect(user.data_invalid_json).to be_nil
5359
end

0 commit comments

Comments
 (0)