Skip to content

Commit 624646a

Browse files
authored
Merge pull request #7 from wadetandy/master
Respect ActiveModel 'base' validations pattern
2 parents a081330 + f33529e commit 624646a

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

lib/jsonapi_errorable/serializers/validation.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,18 @@ def errors
1616
messages.map do |message|
1717
meta = { attribute: attribute, message: message }.merge(@relationship_message)
1818
meta = { relationship: meta } if @relationship_message.present?
19+
20+
detail = "#{attribute.capitalize} #{message}"
21+
22+
if attribute.to_s.downcase == 'base'
23+
detail = message
24+
end
25+
1926
{
2027
code: 'unprocessable_entity',
2128
status: '422',
2229
title: 'Validation Error',
23-
detail: "#{attribute.capitalize} #{message}",
30+
detail: detail,
2431
source: { pointer: pointer_for(object, attribute) },
2532
meta: meta
2633
}

spec/serializers/serializable_validation_spec.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,32 @@
4343
]
4444
)
4545
end
46+
47+
context 'when the error attribute is "base"' do
48+
let(:errors_hash) { { base: ["Model is invalid"] } }
49+
50+
before do
51+
allow(object).to receive(:respond_to?).with(:base) { true }
52+
end
53+
54+
it 'should not render the attribute in the message detail' do
55+
expect(subject).to eq(
56+
[
57+
{
58+
code: 'unprocessable_entity',
59+
status: '422',
60+
title: "Validation Error",
61+
detail: "Model is invalid",
62+
source: { pointer: '/data/attributes/base' },
63+
meta: {
64+
attribute: :base,
65+
message: "Model is invalid"
66+
}
67+
}
68+
]
69+
)
70+
end
71+
end
4672
end
4773

4874
context 'when the error is on a relationship' do

0 commit comments

Comments
 (0)