Skip to content

Commit 993842a

Browse files
committed
Respect ActiveModel 'base' validations pattern
It is a common pattern for activerecord and activemodel models to indicate errors that are not on a given field but rather on the entire model by adding an error to the "base" attribute. In this case the message tends to be a complete sentence about the model state, rather than a clause appended to the attribute name ("can't be blank"). In this case, we don't want to append "Base" to the beginning of the error message.
1 parent a081330 commit 993842a

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

lib/jsonapi_errorable/serializers/validation.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,19 @@ 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+
21+
detail = "#{attribute.capitalize} #{message}"
22+
23+
if attribute.to_s.downcase == 'base'
24+
detail = message
25+
end
26+
1927
{
2028
code: 'unprocessable_entity',
2129
status: '422',
2230
title: 'Validation Error',
23-
detail: "#{attribute.capitalize} #{message}",
31+
detail: detail,
2432
source: { pointer: pointer_for(object, attribute) },
2533
meta: meta
2634
}

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)