Yandri
Yandri

Reputation: 41

RAILS: Does ActiveRecord#persisted? actually queries the database?

Per the documentation, I know it checks wether the object is a new_record or is_destroyed, but does it do this just based on the objects's current state like having an id already set or overall not being nil? Or does it try to perform a query to see if it finds anything matching?

Upvotes: 2

Views: 693

Answers (1)

Ryenski
Ryenski

Reputation: 9692

No, persisted? does not query the database. It merely checks the values of the object's @destroyed or @new_record variables.

See https://github.com/rails/rails/blob/6-1-stable/activerecord/lib/active_record/persistence.rb#L444

# Returns true if the record is persisted, i.e. it's not a new record and it was
# not destroyed, otherwise returns false.
def persisted?
  !(@new_record || @destroyed)
end

@new_record is set to true when the object is instantiated, then false after the record is created. Otherwise it is nil. @destroyed is set to true after the object is destroyed, otherwise it is nil.

At no point does this method hit the database.

If that is your goal, you can use exists? to query the database using the ID:

> User.exists?(user.id)
  User Exists? (5.5ms)  SELECT 1 AS one FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", "123"], ["LIMIT", 1]]
=> true
> User.exists?('321')
  User Exists? (0.4ms)  SELECT 1 AS one FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", nil], ["LIMIT", 1]]
=> false

Upvotes: 6

Related Questions