1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Add ActiveRecord::Base#previously_persisted?

Returns `true` if the object has been previously persisted but now it has been deleted.

This is a follow up of https://github.com/rails/rails/pull/42256/files#r641914920
This commit is contained in:
Jacopo 2021-06-04 13:02:54 +02:00
parent ac48eed08f
commit 851898114b
5 changed files with 19 additions and 2 deletions

View file

@ -1,3 +1,7 @@
* Add `ActiveRecord::Base#previously_persisted?`
Returns `true` if the object has been previously persisted but now it has been deleted.
* Deprecate `partial_writes` in favor of `partial_inserts` and `partial_updates`.
This allows to have a different behavior on update and create.

View file

@ -467,6 +467,11 @@ module ActiveRecord
@previously_new_record
end
# Returns true if this object was previously persisted but now it has been deleted.
def previously_persisted?
!new_record? && destroyed?
end
# Returns true if this object has been destroyed, otherwise returns false.
def destroyed?
@destroyed

View file

@ -800,6 +800,14 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal false, Topic.find(1).previously_new_record?
end
def test_previously_persisted_returns_boolean
assert_equal false, Topic.new.previously_persisted?
assert_equal false, Topic.new.destroy.previously_persisted?
assert_equal false, Topic.first.previously_persisted?
assert_equal true, Topic.first.destroy.previously_persisted?
assert_equal true, Topic.first.delete.previously_persisted?
end
def test_dup
topic = Topic.find(1)
duped_topic = nil

View file

@ -14,6 +14,7 @@ module ActiveRecord
assert cloned.persisted?, "topic persisted"
assert_not cloned.new_record?, "topic is not new"
assert_not cloned.previously_new_record?, "topic was not previously new"
assert_not cloned.previously_persisted?, "topic was not previously persisted"
end
def test_stays_frozen

View file

@ -293,9 +293,8 @@ class ActiveStorage::Blob < ActiveStorage::Record
# blobs. Note, though, that deleting the file off the service will initiate an HTTP connection to the service, which may
# be slow or prevented, so you should not use this method inside a transaction or in callbacks. Use #purge_later instead.
def purge
previously_persisted = persisted?
destroy
delete if previously_persisted
delete if previously_persisted?
rescue ActiveRecord::InvalidForeignKey
end