diff --git a/lib/json_api_client/resource.rb b/lib/json_api_client/resource.rb index 10f334c2..e964cfb3 100644 --- a/lib/json_api_client/resource.rb +++ b/lib/json_api_client/resource.rb @@ -411,11 +411,7 @@ def save if last_result_set.has_errors? last_result_set.errors.each do |error| - if error.source_parameter - errors.add(self.class.key_formatter.unformat(error.source_parameter), error.title || error.detail) - else - errors.add(:base, error.title || error.detail) - end + add_error(error) end false else @@ -450,6 +446,20 @@ def inspect protected + def add_error(error) + if error.source_parameter + error_attribute = self.class.key_formatter.unformat(error.source_parameter) + + if error.code && respond_to?(error_attribute) + errors.add(error_attribute, error.code.to_sym) + else + errors.add(error_attribute, error.title || error.detail) + end + else + errors.add(:base, error.title || error.detail) + end + end + def method_missing(method, *args) association = association_for(method) diff --git a/test/unit/server_side_error_test.rb b/test/unit/server_side_error_test.rb index bb215bb0..b833eb60 100644 --- a/test/unit/server_side_error_test.rb +++ b/test/unit/server_side_error_test.rb @@ -38,7 +38,7 @@ def test_can_handle_key_formatted_attribute_validation_strings .to_return(headers: {content_type: "application/vnd.api+json"}, body: { errors: [{source: {pointer: "/data/attributes/email-address"}, title: "Email address is invalid"}] }.to_json) - + user = User.create(name: 'Bob', email_address: 'invalid email') assert !user.persisted? assert user.errors.present? @@ -46,4 +46,19 @@ def test_can_handle_key_formatted_attribute_validation_strings end end -end \ No newline at end of file + def test_can_handle_key_formatted_attribute_validation_codes + with_altered_config(User, :json_key_format => :dasherized_key) do + stub_request(:post, "http://example.com/users") + .to_return(headers: {content_type: "application/vnd.api+json"}, body: { + errors: [{source: {pointer: "/data/attributes/email-address"}, title: "Email address is invalid", code: "invalid"}] + }.to_json) + + user = User.create(name: 'Bob', email_address: 'invalid email') + assert !user.persisted? + assert user.errors.present? + assert_equal ["is invalid"], user.errors[:email_address] + assert_equal [{error: :invalid}], user.errors.details[:email_address] if user.errors.respond_to?(:details) + end + end + +end