Skip to content

Commit dbc6469

Browse files
johvetTate Thurston
authored andcommitted
Validation errors on the model instance should return the correct pointer value
1 parent d6982d5 commit dbc6469

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

lib/jsonapi/active_model_error_serializer.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ class ActiveModelErrorSerializer < ErrorSerializer
4949
{ pointer: "/data/attributes/#{error_key}" }
5050
elsif rels.include?(error_key)
5151
{ pointer: "/data/relationships/#{error_key}" }
52+
elsif error_key == :base
53+
{ pointer: "/data" }
5254
else
5355
{ pointer: '' }
5456
end

spec/dummy.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ def self.ransackable_associations(auth_object = nil)
4343
class Note < ActiveRecord::Base
4444
validates_format_of :title, without: /BAD_TITLE/
4545
validates_numericality_of :quantity, less_than: 100, if: :quantity?
46+
validate :title_check
4647
belongs_to :user, required: true
4748

4849
def self.ransackable_associations(auth_object = nil)
@@ -52,6 +53,11 @@ def self.ransackable_associations(auth_object = nil)
5253
def self.ransackable_attributes(auth_object = nil)
5354
%w(created_at id quantity title updated_at user_id)
5455
end
56+
57+
# Provide a validation adding an error to the model's base
58+
def title_check
59+
errors.add(:base, :invalid) if title == 'n/a'
60+
end
5561
end
5662

5763
class CustomNoteSerializer

spec/errors_spec.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,27 @@
138138
.to eq('pointer' => '/data/attributes/title')
139139
end
140140
end
141+
142+
context 'with a validation error on the class' do
143+
let(:params) do
144+
payload = note_params.dup
145+
payload[:data][:attributes][:title] = 'n/a'
146+
payload
147+
end
148+
149+
it do
150+
expect(response).to have_http_status(:unprocessable_entity)
151+
expect(response_json['errors'].size).to eq(1)
152+
expect(response_json['errors'][0]['status']).to eq('422')
153+
expect(response_json['errors'][0]['code']).to include('invalid')
154+
expect(response_json['errors'][0]['title'])
155+
.to eq(Rack::Utils::HTTP_STATUS_CODES[422])
156+
expect(response_json['errors'][0]['source'])
157+
.to eq('pointer' => '/data')
158+
expect(response_json['errors'][0]['detail'])
159+
.to eq('is invalid')
160+
end
161+
end
141162
end
142163

143164
context 'with a bad note ID' do

0 commit comments

Comments
 (0)