
Stop Using .any? the Wrong Way in Rails
A single block passed to .any? can silently load thousands of records into memory. No warnings. No errors. Just unnecessary objects. And most Rails developers don’t notice it. You’ve probably used both .any? and .exists? in your Rails app without thinking twice. They both answer the same simple question: Is there at least one record? But under the hood, they can behave very differently. In this article, we’ll look at what actually happens when you call each method, when to use which, and how to avoid a common performance trap. The Basics: Same Query, Same Result If you just need to check whether a relation contains any records at all, both .any? and .exists? generate the same efficient query. user . posts . any? # SELECT 1 AS one FROM "posts" WHERE "posts"."user_id" = 1 LIMIT 1 user . posts . exists? # SELECT 1 AS one FROM "posts" WHERE "posts"."user_id" = 1 LIMIT 1 No objects are loaded into memory. No full table scan. Both methods ask the database a simple yes/no question and return
Continue reading on Dev.to
Opens in a new tab



