Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions lib/json_api_client/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
19 changes: 17 additions & 2 deletions test/unit/server_side_error_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,27 @@ 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?
assert_equal ["Email address is invalid"], user.errors[:email_address]
end
end

end
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