activerecord

Granular Cache Invalidation with touch: true

When a child record changes, you often want the parent cache key to change too. touch: true is a clean primitive for that. It keeps fragment caching sane without complex dependency graphs.

Soft Validation: Normalize + Validate Email

Normalize before validation to avoid “same email, different casing/whitespace” bugs. Keep normalization deterministic and small; put it in the model so imports, consoles, and controllers all behave the same.

N+1 Proof Serialization with preloaded associations

When rendering JSON, the serializer layer can silently trigger extra queries. Force “preload then serialize” so your JSON rendering path is deterministic. This pattern scales well in Rails APIs.

Safe Raw SQL with exec_query + Binds

Sometimes raw SQL is the cleanest approach—just keep it safe. Use exec_query with bind params instead of interpolating values. You get both safety and correctness with types.

Memory-Safe “top tags” aggregation with pluck + group

Tagging systems can be expensive. For quick “top tags” features, compute from the join table with group and count. Avoid loading full taggable records.

Polymorphic “Visible To” Scope with Arel

Authorization filters often become string-SQL soup. Use Arel to build composable scopes that are still readable and safe. This snippet shows a “visible_to(member)” scope with a join and a condition that can evolve without turning into interpolated SQL

Transactional “Reserve Inventory” with SELECT … FOR UPDATE

Inventory systems are concurrency systems. Lock the row, verify available quantity, then write the reservation in the same transaction. It’s the simplest correct starting point.

“Write Amplification” Guard: Only Update Changed Columns

Avoid writing rows when nothing changed—especially in batch jobs. Check changed? or compute the would-be update and skip if identical. This reduces bloat and autovacuum pressure.

Optimistic Locking for Collaborative Edits

If multiple admins edit the same record, use lock_version. Rails will raise on conflicting updates, and you can show a friendly “this changed underneath you” message. It prevents subtle lost updates.

Safer “find or create” with Unique Constraint + Retry

Race conditions happen. The correct “find or create” in production uses a unique constraint and a retry on conflict, not a naive check-then-insert. Let the database serialize the race.

Fast “Exists” Checks with select(1) and LIMIT

Avoid loading whole records when you only need to know if something exists. exists? is good; for complex joins, a scoped select(1).limit(1) can be clearer and keeps the DB workload low.

Bulk Upsert with insert_all + Unique Index

I stopped doing row-by-row imports once they started hammering the DB. In Migration (unique index), I added a real uniqueness guarantee on provider + uid, because bulk writes only stay correct if the database can enforce constraints. Then, in Bulk ups