Custom Validator for “At Least One of” Fields

A tiny custom validator keeps complex presence rules out of controllers. This example enforces that at least one of two fields is present (e.g., text content or an attachment).

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.

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.

Atomic “Read + Mark Processed” with UPDATE … RETURNING

If you have a queue table, avoid races by selecting and updating in one statement. Postgres UPDATE … RETURNING is the simplest building block for a correct custom queue / maintenance pipeline.

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.

Postgres JSONB Partial Index for Feature Flags

If you store flags/settings in JSONB, query performance hinges on indexing. Partial indexes are a great compromise: index only the rows that matter for the hot path (e.g., enabled flags).

Multi-Column Full Text Search with tsvector

For Postgres search beyond trivial ILIKE, maintain a tsvector column and a GIN index. Update it via trigger or application logic. This keeps search fast and predictable even as your dataset grows.

Safer File Attachments: Content Type + Size Validation

Active Storage makes uploads easy; production makes them dangerous. Validate content type and size at the model layer, and keep the error messages user-friendly. This prevents large or unexpected uploads from blowing up costs and processing queues.

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.

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.

Rate Limiting with Redis + Increment Expiry

A simple fixed-window rate limiter is often enough for endpoints like login, password reset, webhooks, or expensive searches. Use atomic Redis INCR + EXPIRE with a stable key and return remaining quota for UX.

Schema-Backed Enums (DB Constraint + Rails enum)

Rails enums are nice, but the DB should enforce allowed values. Use a CHECK constraint (or native enum type) plus the Rails enum mapping. It prevents bad writes from console scripts and future migrations.