date_trunc and Group by Month in ActiveRecord
Group by month in ActiveRecord with PostgreSQL date_trunc. Tested time zone handling, key types, missing months, and what groupdate adds.
The blog
Real solutions to SQL → ActiveRecord translation problems. Learn why your queries break, how to fix them, and what Rails actually generates.
Group by month in ActiveRecord with PostgreSQL date_trunc. Tested time zone handling, key types, missing months, and what groupdate adds.
Write LIKE and ILIKE in ActiveRecord, escape input with sanitize_sql_like, and see which patterns use an index. Tested on Rails 8.1 and PostgreSQL 16.
Sort NULLs last in Rails: Arel nulls_last, the raw string trap on SQLite, an IS NULL fallback and the PostgreSQL index. Tested on Rails 8.1.1.
New to ActiveRecord? These posts explain the mental model differences that cause bugs.
LEFT JOINs that become INNER JOINs, multiple conditions, and association gotchas
joins filters using SQL JOIN. includes prevents N+1 by eager loading. Using the wrong one creates hidden performance problems. Rails 7/8 with SQL output.
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 5-table ActiveRecord join took 8 seconds. Rewriting it as a subquery took it to 200ms. Here's what changed and why the query planner behaves differently.
N+1 queries, includes() side effects, and when ActiveRecord makes things slower
pick is pluck for one row. See the SQL for pick vs pluck.first, why ORDER BY matters, and when to use find_by or exists? instead.
The database had indexes. ActiveRecord queries weren't using them. Here's how ActiveRecord query patterns bypass indexes and how to check EXPLAIN output.
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.
Rails 8.2 for production apps: caching, query performance, concurrency changes, and what actually breaks at scale. No hype, just impact. Updated 2026.