postgres

ruby
class AddUniqueIndexToInventorySnapshots < ActiveRecord::Migration[7.1]
  disable_ddl_transaction!

  def change
    add_index :inventory_snapshots,
              [:warehouse_id, :sku],

Bulk Upsert with insert_all + Unique Index

rails activerecord postgres
by codesnips 3 tabs
ruby
class Article < ApplicationRecord
  scope :ranked, -> { order(score: :desc, id: :desc) }

  scope :after_cursor, ->(cursor) do
    return all if cursor.nil?

Deterministic Sorting with Secondary Key

rails activerecord pagination
by codesnips 4 tabs
sql
-- Product.active.touch_all(:cache_synced_at) for catalog 42
UPDATE "products"
SET "updated_at" = '2024-05-01 12:00:00.123456',
    "cache_synced_at" = '2024-05-01 12:00:00.123456'
WHERE "products"."catalog_id" = 42
  AND "products"."status" = 'active';

Use `touch_all` for Efficient “Bump Updated At”

rails activerecord performance
by codesnips 4 tabs
ruby
module KeysetPageable
  extend ActiveSupport::Concern

  included do
    scope :keyset_page, ->(cursor: nil, per: 20) do
      per = per.to_i.clamp(1, 100)

Safe Pagination with Keyset (No OFFSET)

rails activerecord performance
by codesnips 3 tabs
sql
ALTER TABLE documents ADD COLUMN version BIGINT NOT NULL DEFAULT 0;

Optimistic locking with a version column

go postgres sql
by Leah Thompson 2 tabs
ruby
class Document < ApplicationRecord
  belongs_to :account

  validates :source_url, presence: true

  before_save :normalize_checksum

Prevent Long Transactions with after_save_commit for Heavy Work

rails activerecord background-jobs
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  belongs_to :customer

  scope :for_export, -> {
    select(:id, :reference, :total_cents, :currency, :created_at, :customer_id)
      .where.not(exported_at: nil)

Avoid Memory Blowups: find_each + select Columns

rails activerecord performance
by codesnips 3 tabs
ruby
class CreateSubscriptions < ActiveRecord::Migration[7.1]
  STATUSES = %w[pending active past_due canceled].freeze

  def change
    create_table :subscriptions do |t|
      t.references :account, null: false, foreign_key: true

Schema-Backed Enums (DB Constraint + Rails enum)

rails postgres schema
by codesnips 3 tabs
ruby
class Category < ApplicationRecord
  has_many :products, dependent: :restrict_with_error
  has_many :subcategories,
           class_name: "Category",
           foreign_key: :parent_id,
           dependent: :restrict_with_error

Safer Deletion with dependent: :restrict_with_error

rails activerecord data-integrity
by codesnips 4 tabs
sql
CREATE TABLE daily_events (
    id          BIGSERIAL PRIMARY KEY,
    category    TEXT        NOT NULL,
    item_id     BIGINT      NOT NULL,
    score       NUMERIC(10,2) NOT NULL DEFAULT 0,
    occurred_at TIMESTAMPTZ NOT NULL DEFAULT now()

Database-Driven “Daily Top” with window functions

postgres sql analytics
by codesnips 3 tabs
ruby
class Post < ApplicationRecord
  has_many :comments, dependent: :destroy

  # comments_count is maintained by counter_cache on Comment#belongs_to

  scope :stale_comment_counts, lambda {

Counter Cache Repair Job (Consistency Tooling)

rails activerecord counter-cache
by codesnips 3 tabs
typescript
export type CheckResult = { name: string; status: 'up' | 'down'; durationMs: number; error?: string };
export type Check = () => Promise<void>;

function withTimeout(fn: Check, ms: number): Promise<void> {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms);

Health checks with readiness + liveness

reliability fastify kubernetes
by codesnips 3 tabs