Rails 7 adds ActiveRecord::Base#previously_persisted?


default-enum-in-rails

If you have not installed Rails 7 yet, please follow our other article on How to install rails 7 to do it in 10 seconds.

Rails 7 adds method previously_persisted? in ActiveRecord::Base, which enables you to check if the object was existed previously and now is destroyed or deleted.

Example

# finds post by id 1
post = Post.find(1) 

# delete/destroy post
post.destroy
# or
post.delete

# check if object persisted previously?
post.previously_persisted?
=> true

Implementation

The implementation of this method is as simple as checking if the record is not new and is destroyed

  def previously_persisted?
    !new_record? && destroyed?
  end


See more from Rails 7

  1. ActiveRecord::Relation#excluding

Recommended Posts

Rails 5 adds OR Activerecord method
This or method was introduced in Rails 5, It returns a new ActiveRecord::Relation which is...
Descendants vs Subclasses in Ruby
Descendants has been a part of Rails ActiveSupport::DescendantsTracker for quite a while. However, Class#subsclasses is...
Ruby 3.1 adds subclasses method
Ruby 3.1 adds Class#subclasses method, which returns an array of subclasses directly inheriting from the...