activerecord

Model validations for data integrity

Validations ensure data consistency before persisting to the database, catching invalid states early in the request lifecycle. I combine presence validations for required fields, uniqueness constraints that map to database indexes, and format validati

Query objects for complex ActiveRecord queries

When queries become too complex for scopes—involving multiple joins, subqueries, or raw SQL fragments—I extract them into dedicated query objects. Each query object is a plain Ruby class that encapsulates one specific query pattern and returns an Acti

Transactional Outbox for Reliable Event Publishing

I used a transactional outbox when I needed my database write and my event publish to succeed or fail together. In OutboxEvent model, I treated the outbox like a queue: a durable row per event, a dedupe_key for idempotency, and a ready scope that pull

Polymorphic associations for flexible relationships

Polymorphic associations allow a model to belong to multiple other models through a single association, which is useful for shared behaviors like comments, likes, or attachments. Instead of separate post_id and article_id columns, a polymorphic associ

Bulk operations with ActiveRecord import

Inserting thousands of records one-by-one is prohibitively slow due to the overhead of individual INSERT statements. The activerecord-import gem provides bulk insert capabilities that compile multiple records into a single multi-row INSERT, dramatical

Per-Request Query Budget (Detect Runaway Pages)

Set a rough query budget per request in dev/test and alert when exceeded. This is a pragmatic way to keep performance regressions visible without requiring a full APM setup.

Strict Loading to Catch N+1 in Development

I enable strict loading when I want N+1 bugs to fail loudly during development instead of quietly shipping to production. In Enable strict_loading on associations, I mark the relationships that routinely get iterated (has_many :line_items and belongs_