diff --git a/lib/json_api_client/resource.rb b/lib/json_api_client/resource.rb index cb176ca9..fd531f52 100644 --- a/lib/json_api_client/resource.rb +++ b/lib/json_api_client/resource.rb @@ -315,6 +315,7 @@ def _build_connection(rebuild = false) def initialize(params = {}) params = params.symbolize_keys @persisted = nil + @destroyed = nil self.links = self.class.linker.new(params.delete(:links) || {}) self.relationships = self.class.relationship_linker.new(self.class, params.delete(:relationships) || {}) self.attributes = self.class.default_attributes.merge(params) @@ -355,14 +356,26 @@ def mark_as_persisted! # # @return [Boolean] def persisted? - !!@persisted && has_attribute?(self.class.primary_key) + !!@persisted && !destroyed? && has_attribute?(self.class.primary_key) + end + + # Mark the record as destroyed + def mark_as_destroyed! + @destroyed = true + end + + # Whether or not this record has been destroyed to the database previously + # + # @return [Boolean] + def destroyed? + !!@destroyed end # Returns true if this is a new record (never persisted to the database) # # @return [Boolean] def new_record? - !persisted? + !persisted? && !destroyed? end # When we represent this resource as a relationship, we do so with id & type @@ -449,8 +462,7 @@ def destroy fill_errors false else - self.attributes.clear - self.relationships.attributes.clear + mark_as_destroyed! self.relationships.last_result_set = nil _clear_cached_relationships true diff --git a/test/unit/creation_test.rb b/test/unit/creation_test.rb index b5e3f2d9..abcf78cd 100644 --- a/test/unit/creation_test.rb +++ b/test/unit/creation_test.rb @@ -69,8 +69,10 @@ def test_can_create_with_new_record_and_save title: "Rails is Omakase" }) + assert article.new_record? assert article.save assert article.persisted? + assert_equal(false, article.new_record?) assert_equal "1", article.id end diff --git a/test/unit/destroying_test.rb b/test/unit/destroying_test.rb index 5b2896aa..fc52d72f 100644 --- a/test/unit/destroying_test.rb +++ b/test/unit/destroying_test.rb @@ -11,14 +11,29 @@ class CallbackTest < TestResource end def test_destroy - stub_request(:delete, "http://example.com/users/6") + stub_request(:get, "http://example.com/users/1") + .to_return(headers: {content_type: "application/vnd.api+json"}, body: { + data: [ + {id: 1, attributes: {name: "Jeff Ching", email_address: "ching.jeff@gmail.com"}} + ] + }.to_json) + + users = User.find(1) + user = users.first + assert(user.persisted?) + assert_equal(false, user.new_record?) + assert_equal(false, user.destroyed?) + + stub_request(:delete, "http://example.com/users/1") .to_return(headers: {content_type: "application/vnd.api+json"}, body: { data: [] }.to_json) - user = User.new(id: 6) assert(user.destroy, "successful deletion should return truish value") assert_equal(false, user.persisted?) + assert_equal(false, user.new_record?) + assert(user.destroyed?) + assert_equal(1, user.id) end def test_destroy_no_content