Rails 7 adds previously_persisted? method to ActiveRecord
source link: https://blog.saeloun.com/2021/07/06/rails-7-adds-previously_persisted
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Rails 7 adds previously_persisted? method to ActiveRecord
Jul 6, 2021 , by Nishant Samel 1 minute readRails has provided methods like
exists?
to check whether the object is present in the database table or not.persisted?
to check whether the object is not a new record and it is not destroyed from the database.
But no method tells us that the particular object was a part of the database table in the past and now is deleted.
Before Rails 7:
Let’s say we have a Customer
model with the name
attribute.
It has a row with the name “John Doe”.
If we have deleted this entry from the table, we can verify that “John Doe” was our previous customer or not using the following code snippet:
old_customer = Customer.find_by_name('John Doe')
old_customer.destroy!
# check if record existed
!old_customer.new_record? && old_customer.destroyed?
=> true
In Rails 7:
As per the discussion in this
PR,
Rails 7 has added a method previously_persisted?
to ActiveRecord::Base
.
We can now use the previously_persisted?
method on the object directly,
instead of the above conditions.
old_customer = Customer.find_by_name('John Doe')
old_customer.destroy!
old_customer.previously_persisted?
=> true
This method is helpful in the case of the after_destroy
callback,
where we are performing some cleanup activities for associated records.
Check out the PR for more details.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK