Picture of the author

GAURAV VARMA

← BACK TO BLOG

Rails 7 adds ActiveRecord::Base#previously_persisted?


Active Record in Rails provides various methods like exists?, persisted?, destroyed? and many more. Using these methods we can easily determine if an object exists in the database or if an object is an existing record in the database and not a new record.

Using these methods we can quickly determine the state of an object and easily write complex conditional statements that depend on the state of an object. Previously we did not have a method that lets us determine if an object was a part of the database in past but now does not exist.

However, Rails 7 has added previously_persisted? method to ActiveRecord, which returns true if an object has been previously a part of the database records but now has been destroyed.

Let’s assume we have a User model with the name column value John Doe. If this record has been deleted from the database, we can still check if John Doe was a user of our app or not in the past.

Before

Let's say we delete the user with the name John Doe.

1# app/controllers/user_controller.rb
2previous_user = User.find_by_name('John Doe')
3previous_user.destroy!

Now we can check if the user exists in our database.

1# app/controllers/user_controller.rb
2# check if previous_user is destroyed and is not a new user
3if previous_user.destroyed? && !previous_user.new_record?
4  # returns true
5end

Rails 7 onwards

We can use the previously_persisted? method on an object.

Let's delete the user with the name John Doe.

1# app/controllers/user_controller.rb
2previous_user = User.find_by_name('John Doe')
3previous_user.destroy!

Now we can check if the user exists in our database using the previously_persisted? method.

1# app/controllers/user_controller.rb
2previous_user.previously_persisted? # returns true

Check out this pull request for more details.

This article was originally published on this website.