present? vs exists? in Rails

present? and exists? serve the same purpose, i.e. to check if a record exists in the database or not. They do, however, differ in the performance.

present?

present? should only be used if something needs to be done with the object as it loads all the columns of the record into memory.

1
Post.where(id: 1).present?

It will fire the following query:

1
Post Load (0.4ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = $1  [["id", 1]]

This is wasteful if we only need to check the presence, as it is loading all the columns in memory.

exists?

exists? limits the query to one record and doesn’t select any columns.

1
Post.where(id: 1).exists?

It will fire the following query:

1
Post Exists? (0.4ms)  SELECT 1 AS one FROM "posts" WHERE "posts"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]

So, exists? should be an obvious approach if we only need to check the existence.