@@ -294,9 +294,11 @@ def errors
294294 end
295295
296296 class ValidationErrors < Error
297- attr_accessor :messages
298- def initialize ( messages )
299- @messages = messages
297+ attr_reader :error_messages , :resource_associations
298+
299+ def initialize ( resource )
300+ @error_messages = resource . model . errors . messages
301+ @resource_associations = resource . class . _associations . keys
300302 @key_formatter = JSONAPI . configuration . key_formatter
301303 end
302304
@@ -305,16 +307,26 @@ def format_key(key)
305307 end
306308
307309 def errors
308- messages . inject ( [ ] ) do |arr , element |
309- arr . concat (
310- element [ 1 ] . map do |message |
311- JSONAPI ::Error . new ( code : JSONAPI ::VALIDATION_ERROR ,
312- status : :unprocessable_entity ,
313- title : "#{ format_key ( element [ 0 ] ) } - #{ message } " ,
314- detail : message ,
315- path : "/#{ element [ 0 ] } " )
316- end
317- )
310+ error_messages . flat_map do |attr_key , messages |
311+ messages . map { |message | json_api_error ( attr_key , message ) }
312+ end
313+ end
314+
315+ private
316+
317+ def json_api_error ( attr_key , message )
318+ JSONAPI ::Error . new ( code : JSONAPI ::VALIDATION_ERROR ,
319+ status : :unprocessable_entity ,
320+ title : "#{ format_key ( attr_key ) } - #{ message } " ,
321+ detail : message ,
322+ source : { pointer : pointer ( attr_key ) } )
323+ end
324+
325+ def pointer ( attr_or_association_name )
326+ if resource_associations . include? ( attr_or_association_name )
327+ "/data/relationships/#{ attr_or_association_name } "
328+ else
329+ "/data/attributes/#{ attr_or_association_name } "
318330 end
319331 end
320332 end
@@ -358,7 +370,7 @@ class InvalidPageValue < Error
358370 def initialize ( page , value , msg = nil )
359371 @page = page
360372 @value = value
361- @msg = msg . nil? ? "#{ value } is not a valid value for #{ page } page parameter." : msg
373+ @msg = msg || "#{ value } is not a valid value for #{ page } page parameter."
362374 end
363375
364376 def errors
0 commit comments