Skip to content

Commit 5cfdf92

Browse files
authored
Merge pull request #330 from gaorlov/primary_key_fix
Deletion for primary keys
2 parents 4ca6148 + 0b9ead2 commit 5cfdf92

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

lib/json_api_client/resource.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ def as_relation
402402
#
403403
# @return [Hash] Representation of this object as JSONAPI object
404404
def as_json_api(*)
405-
attributes.slice(:id, :type).tap do |h|
405+
attributes.slice(self.class.primary_key, :type).tap do |h|
406406
relationships_for_serialization.tap do |r|
407407
h[:relationships] = self.class.key_formatter.format_keys(r) unless r.empty?
408408
end
@@ -411,11 +411,11 @@ def as_json_api(*)
411411
end
412412

413413
def as_json(*)
414-
attributes.slice(:id, :type).tap do |h|
414+
attributes.slice(self.class.primary_key, :type).tap do |h|
415415
relationships.as_json.tap do |r|
416416
h[:relationships] = r unless r.empty?
417417
end
418-
h[:attributes] = attributes.except(:id, :type).as_json
418+
h[:attributes] = attributes.except(self.class.primary_key, :type).as_json
419419
end
420420
end
421421

@@ -512,7 +512,7 @@ def reset_request_select!(*resource_types)
512512
end
513513

514514
def path_attributes
515-
_belongs_to_params.merge attributes.slice('id').symbolize_keys
515+
_belongs_to_params.merge attributes.slice( self.class.primary_key ).symbolize_keys
516516
end
517517

518518
protected

test/unit/destroying_test.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,33 @@ def test_destroy
3636
assert_equal(1, user.id)
3737
end
3838

39+
def test_destroy_custom_primary_key
40+
stub_request(:get, "http://example.com/user_preferences/105")
41+
.to_return(headers: {content_type: "application/vnd.api+json"}, body: {
42+
data: [
43+
{attributes: { user_id: 105, name: "Jeff Ching", email_address: "ching.jeff@gmail.com"}}
44+
]
45+
}.to_json)
46+
47+
$print_load = true
48+
user_prefrence = UserPreference.find(105).first
49+
assert(user_prefrence.persisted?)
50+
$print_load = false
51+
assert_equal(false, user_prefrence.new_record?)
52+
assert_equal(false, user_prefrence.destroyed?)
53+
54+
stub_request(:delete, "http://example.com/user_preferences/105")
55+
.to_return(headers: {content_type: "application/vnd.api+json"}, body: {
56+
data: []
57+
}.to_json)
58+
59+
assert(user_prefrence.destroy, "successful deletion should return truish value")
60+
assert_equal(false, user_prefrence.persisted?)
61+
assert_equal(false, user_prefrence.new_record?)
62+
assert(user_prefrence.destroyed?)
63+
assert_equal(105, user_prefrence.user_id)
64+
end
65+
3966
def test_destroy_no_content
4067
stub_request(:delete, "http://example.com/users/6")
4168
.to_return(headers: {content_type: "application/vnd.api+json"}, body: nil)

0 commit comments

Comments
 (0)