Rails 7 adds previously_persisted? method to ActiveRecord

Rails 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.

Need help on your Ruby on Rails or React project?

Join Our Newsletter