ActiveRecord where vs find_by — Which to Use When
where returns a relation, find_by returns one record or nil. Here's when each is correct, what breaks if you pick wrong, and Rails 7/8 production patterns.
A curated library of common SQL patterns and their correct ActiveRecord equivalents, serving as a reference for real-world Rails queries.
where returns a relation, find_by returns one record or nil. Here's when each is correct, what breaks if you pick wrong, and Rails 7/8 production patterns.
Using each on large ActiveRecord collections loads all records into memory. find_each batches them. Here's why background jobs need this and the gotchas.
ActiveRecord was running 47 identical queries per request. Bullet found the pattern. Here's what caused it, how to read Bullet's output, and the fix.
posts.count hit the database on every request and brought down production. Here's how counter cache fixes it, what to watch for, and how to backfill safely.
When ActiveRecord's abstraction costs 80% of query performance, raw SQL is the right call. Here's how to know when to drop down and do it safely in Rails.
I added includes() to every association to fix N+1 queries. Performance got worse. Here's why eager loading isn't always the answer and when to use each.
Added includes() to every N+1 warning. Response times went up, not down. Here's what went wrong and how to choose between eager loading and joins.
I read Agile Web Development with Rails cover to cover. I still couldn't write production queries. Here's the gap between theory and what actually works.
I taught SQL for 5 years. Teaching ActiveRecord broke every analogy I had. Here's what I had to unlearn — and the new model that actually works for beginners.
As a DBA, Rails felt wrong. SQL was cleaner. Then I hit maintenance hell on a raw-SQL codebase and changed my mind. Here's what shifted.
Every SQL to ActiveRecord converter gave me different output for the same query. Here's why — and what that tells you about how ActiveRecord actually works.
SQL JOINs made sense. ActiveRecord's includes() confused me for weeks. Here's the mental model that finally made it click and when to use each.
My ActiveRecord query looked clean. The SQL was a full table scan. Here's what I missed and why I check EXPLAIN ANALYZE on every non-trivial query now.
SQL fluency creates specific blind spots when learning ActiveRecord. Here's where the mental model breaks, and how to reframe it so the ORM finally makes sense.
ActiveRecord isn't SQL with Ruby syntax — it's a different mental model. Here's why the shift trips up SQL-fluent developers and how to make it click.